<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>GrPPI: gMock Cookbook</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="logo.svg"/></td>
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname">GrPPI
   &#160;<span id="projectnumber">1.0</span>
   </div>
   <div id="projectbrief">Generic and Reusable Parallel Pattern Interface</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.2 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(function() {
  initMenu('',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

</div><!-- top -->
<div class="PageDoc"><div class="header">
  <div class="headertitle">
<div class="title">gMock Cookbook </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>You can find recipes for using gMock here. If you haven't yet, please read <a class="el" href="_g_mock_for_dummies.html#md__home_jdgarcia_repos_github_arcosuc3m_grppi_cmake_build_debug_googletest_src_docs_gmock_for_dummies">the dummy guide</a> first to make sure you understand the basics.</p>
<p>{: .callout .note} <b>Note:</b> gMock lives in the <code>testing</code> name space. For readability, it is recommended to write <code>using ::testing::Foo;</code> once in your file before using the name <code>Foo</code> defined by gMock. We omit such <code>using</code> statements in this section for brevity, but you should do it in your own code.</p>
<h1><a class="anchor" id="autotoc_md134"></a>
Creating Mock Classes</h1>
<p><a class="el" href="class_mock.html">Mock</a> classes are defined as normal classes, using the <code>MOCK_METHOD</code> macro to generate mocked methods. The macro gets 3 or 4 parameters:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MyMock {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(ReturnType, MethodName, (Args...));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(ReturnType, MethodName, (Args...), (Specs...));</div>
<div class="line">};</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h_html_a05ffc29d0784b131ee178da190d31397"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a></div><div class="ttdeci">#define MOCK_METHOD(...)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-function-mocker.h:77</div></div>
</div><!-- fragment --><p>The first 3 parameters are simply the method declaration, split into 3 parts. The 4th parameter accepts a closed list of qualifiers, which affect the generated method:</p>
<ul>
<li>**<code>const</code>** - Makes the mocked method a <code>const</code> method. Required if overriding a <code>const</code> method.</li>
<li>**<code>override</code>** - Marks the method with <code>override</code>. Recommended if overriding a <code>virtual</code> method.</li>
<li>**<code>noexcept</code>** - Marks the method with <code>noexcept</code>. Required if overriding a <code>noexcept</code> method.</li>
<li>**<code>Calltype(...)</code>** - Sets the call type for the method (e.g. to <code>STDMETHODCALLTYPE</code>), useful in Windows.</li>
<li>**<code>ref(...)</code>** - Marks the method with the reference qualification specified. Required if overriding a method that has reference qualifications. Eg <code>ref(&amp;)</code> or <code>ref(&amp;&amp;)</code>.</li>
</ul>
<h2><a class="anchor" id="autotoc_md135"></a>
Dealing with unprotected commas</h2>
<p>Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent <code>MOCK_METHOD</code> from parsing its arguments correctly:</p>
<p>{: .bad} </p><div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(std::pair&lt;bool, int&gt;, GetPair, ());  <span class="comment">// Won&#39;t compile!</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, CheckMap, (std::map&lt;int, double&gt;, <span class="keywordtype">bool</span>));  <span class="comment">// Won&#39;t compile!</span></div>
<div class="line">};</div>
</div><!-- fragment --><p>Solution 1 - wrap with parentheses:</p>
<p>{: .good} </p><div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>((std::pair&lt;bool, int&gt;), GetPair, ());</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, CheckMap, ((std::map&lt;int, double&gt;), <span class="keywordtype">bool</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><p>Note that wrapping a return or argument type with parentheses is, in general, invalid C++. <code>MOCK_METHOD</code> removes the parentheses.</p>
<p>Solution 2 - define an alias:</p>
<p>{: .good} </p><div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">using</span> BoolAndInt = std::pair&lt;bool, int&gt;;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(BoolAndInt, GetPair, ());</div>
<div class="line">  <span class="keyword">using</span> MapIntDouble = std::map&lt;int, double&gt;;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, CheckMap, (MapIntDouble, <span class="keywordtype">bool</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md136"></a>
Mocking Private or Protected Methods</h2>
<p>You must always put a mock method definition (<code>MOCK_METHOD</code>) in a <code>public:</code> section of the mock class, regardless of the method being mocked being <code>public</code>, <code>protected</code>, or <code>private</code> in the base class. This allows <code>ON_CALL</code> and <code>EXPECT_CALL</code> to reference the mock function from outside of the mock class. (Yes, C++ allows a subclass to change the access level of a virtual function in the base class.) Example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> Transform(Gadget* g) = 0;</div>
<div class="line"> </div>
<div class="line"> <span class="keyword">protected</span>:</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> Resume();</div>
<div class="line"> </div>
<div class="line"> <span class="keyword">private</span>:</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">int</span> GetTimeOut();</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, Transform, (Gadget* g), (<span class="keyword">override</span>));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The following must be in the public section, even though the</span></div>
<div class="line">  <span class="comment">// methods are protected or private in the base class.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Resume, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, GetTimeOut, (), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md137"></a>
Mocking Overloaded Methods</h2>
<p>You can mock overloaded functions as usual. No special attention is required:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Foo {</div>
<div class="line">  ...</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Must be virtual as we&#39;ll inherit from Foo.</span></div>
<div class="line">  <span class="keyword">virtual</span> ~Foo();</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Overloaded on the types and/or numbers of arguments.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">int</span> Add(Element x);</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">int</span> Add(<span class="keywordtype">int</span> times, Element x);</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Overloaded on the const-ness of this object.</span></div>
<div class="line">  <span class="keyword">virtual</span> Bar&amp; GetBar();</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keyword">const</span> Bar&amp; GetBar() <span class="keyword">const</span>;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line">  ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, Add, (Element x), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, Add, (<span class="keywordtype">int</span> times, Element x), (<span class="keyword">override</span>));</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(Bar&amp;, GetBar, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keyword">const</span> Bar&amp;, GetBar, (), (<span class="keyword">const</span>, <span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><p>{: .callout .note} <b>Note:</b> if you don't mock all versions of the overloaded method, the compiler will give you a warning about some methods in the base class being hidden. To fix that, use <code>using</code> to bring them in scope:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">using</span> Foo::Add;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, Add, (Element x), (<span class="keyword">override</span>));</div>
<div class="line">  <span class="comment">// We don&#39;t want to mock int Add(int times, Element x);</span></div>
<div class="line">  ...</div>
<div class="line">};</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md138"></a>
Mocking Class Templates</h2>
<p>You can mock class templates just like any class.</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Elem&gt;</div>
<div class="line"><span class="keyword">class </span>StackInterface {</div>
<div class="line">  ...</div>
<div class="line">  <span class="comment">// Must be virtual as we&#39;ll inherit from StackInterface.</span></div>
<div class="line">  <span class="keyword">virtual</span> ~StackInterface();</div>
<div class="line"> </div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">int</span> GetSize() <span class="keyword">const</span> = 0;</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> Push(<span class="keyword">const</span> Elem&amp; x) = 0;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Elem&gt;</div>
<div class="line"><span class="keyword">class </span>MockStack : <span class="keyword">public</span> StackInterface&lt;Elem&gt; {</div>
<div class="line">  ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, GetSize, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Push, (<span class="keyword">const</span> Elem&amp; x), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><h2><a class="anchor" id="MockingNonVirtualMethods"></a>
Mocking Non-virtual Methods</h2>
<p>gMock can mock non-virtual functions to be used in Hi-perf dependency injection.</p>
<p>In this case, instead of sharing a common base class with the real class, your mock class will be <em>unrelated</em> to the real class, but contain methods with the same signatures. The syntax for mocking non-virtual methods is the <em>same</em> as mocking virtual methods (just don't add <code>override</code>):</p>
<div class="fragment"><div class="line"><span class="comment">// A simple packet stream class.  None of its members is virtual.</span></div>
<div class="line"><span class="keyword">class </span>ConcretePacketStream {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">void</span> AppendPacket(Packet* new_packet);</div>
<div class="line">  <span class="keyword">const</span> Packet* GetPacket(<span class="keywordtype">size_t</span> packet_number) <span class="keyword">const</span>;</div>
<div class="line">  <span class="keywordtype">size_t</span> NumberOfPackets() <span class="keyword">const</span>;</div>
<div class="line">  ...</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// A mock packet stream class.  It inherits from no other, but defines</span></div>
<div class="line"><span class="comment">// GetPacket() and NumberOfPackets().</span></div>
<div class="line"><span class="keyword">class </span>MockPacketStream {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keyword">const</span> Packet*, GetPacket, (<span class="keywordtype">size_t</span> packet_number), (<span class="keyword">const</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">size_t</span>, NumberOfPackets, (), (<span class="keyword">const</span>));</div>
<div class="line">  ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>Note that the mock class doesn't define <code>AppendPacket()</code>, unlike the real class. That's fine as long as the test doesn't need to call it.</p>
<p>Next, you need a way to say that you want to use <code>ConcretePacketStream</code> in production code, and use <code>MockPacketStream</code> in tests. Since the functions are not virtual and the two classes are unrelated, you must specify your choice at <em>compile time</em> (as opposed to run time).</p>
<p>One way to do it is to templatize your code that needs to use a packet stream. More specifically, you will give your code a template type argument for the type of the packet stream. In production, you will instantiate your template with <code>ConcretePacketStream</code> as the type argument. In tests, you will instantiate the same template with <code>MockPacketStream</code>. For example, you may write:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> PacketStream&gt;</div>
<div class="line"><span class="keywordtype">void</span> CreateConnection(PacketStream* stream) { ... }</div>
<div class="line"> </div>
<div class="line"><span class="keyword">template</span> &lt;<span class="keyword">class</span> PacketStream&gt;</div>
<div class="line"><span class="keyword">class </span>PacketReader {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">void</span> ReadPackets(PacketStream* stream, <span class="keywordtype">size_t</span> packet_num);</div>
<div class="line">};</div>
</div><!-- fragment --><p>Then you can use <code>CreateConnection&lt;ConcretePacketStream&gt;()</code> and <code>PacketReader&lt;ConcretePacketStream&gt;</code> in production code, and use <code>CreateConnection&lt;MockPacketStream&gt;()</code> and <code>PacketReader&lt;MockPacketStream&gt;</code> in tests.</p>
<div class="fragment"><div class="line">MockPacketStream mock_stream;</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_stream, ...)...;</div>
<div class="line">.. set more expectations on mock_stream ...</div>
<div class="line">PacketReader&lt;MockPacketStream&gt; reader(&amp;mock_stream);</div>
<div class="line">... exercise reader ...</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h_html_a535a6156de72c1a2e25a127e38ee5232"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a></div><div class="ttdeci">#define EXPECT_CALL(obj, call)</div></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md139"></a>
Mocking Free Functions</h2>
<p>It's possible to use gMock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).</p>
<p>Instead of calling a free function (say, <code>OpenFile</code>) directly, introduce an interface for it and have a concrete subclass that calls the free function:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>FileInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> Open(<span class="keyword">const</span> <span class="keywordtype">char</span>* path, <span class="keyword">const</span> <span class="keywordtype">char</span>* mode) = 0;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>File : <span class="keyword">public</span> FileInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> Open(<span class="keyword">const</span> <span class="keywordtype">char</span>* path, <span class="keyword">const</span> <span class="keywordtype">char</span>* mode) {</div>
<div class="line">     <span class="keywordflow">return</span> OpenFile(path, mode);</div>
<div class="line">  }</div>
<div class="line">};</div>
</div><!-- fragment --><p>Your code should talk to <code>FileInterface</code> to open a file. Now it's easy to mock out the function.</p>
<p>This may seem like a lot of hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.</p>
<p>If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for <a href="#MockingNonVirtualMethods">mocking non-virtual methods</a>.</p>
<h2><a class="anchor" id="autotoc_md140"></a>
Old-Style &lt;tt&gt;MOCK_METHODn&lt;/tt&gt; Macros</h2>
<p>Before the generic <code>MOCK_METHOD</code> macro <a href="https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2">was introduced in 2018</a>, mocks where created using a family of macros collectively called <code>MOCK_METHODn</code>. These macros are still supported, though migration to the new <code>MOCK_METHOD</code> is recommended.</p>
<p>The macros in the <code>MOCK_METHODn</code> family differ from <code>MOCK_METHOD</code>:</p>
<ul>
<li>The general structure is <code>MOCK_METHODn(MethodName, ReturnType(Args))</code>, instead of <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD(ReturnType, MethodName, (Args))</a></code>.</li>
<li>The number <code>n</code> must equal the number of arguments.</li>
<li>When mocking a const method, one must use <code>MOCK_CONST_METHODn</code>.</li>
<li>When mocking a class template, the macro name must be suffixed with <code>_T</code>.</li>
<li>In order to specify the call type, the macro name must be suffixed with <code>_WITH_CALLTYPE</code>, and the call type is the first macro argument.</li>
</ul>
<p>Old macros and their new equivalents:</p>
<table class="doxtable">
<tr>
<th colspan="2">Simple </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#ac49d366be035ee87b73264a29059cdc7">MOCK_METHOD1(Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD(bool, Foo, (int))</a></code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Const Method </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a6f76aeb56f492cfe538e177b6aa77965">MOCK_CONST_METHOD1(Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code>MOCK_METHOD(bool, Foo, (int), (const))</code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Method in a Class Template </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a8e5b9539726be5c7a13f1aa3bcc1f29f">MOCK_METHOD1_T(Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD(bool, Foo, (int))</a></code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Const Method in a Class Template </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a46dfe8631eee86b15a79aff8a2866621">MOCK_CONST_METHOD1_T(Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code>MOCK_METHOD(bool, Foo, (int), (const))</code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Method with Call Type </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a3ffee4ba10588254eb44e67603e9de71">MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Const Method with Call Type </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a94f4b0954d3d72011acf5f288ca40d42">MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Method with Call Type in a Class Template </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a3028c1938f6b819b64400c426ef1e30d">MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><p class="starttd"><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code> </p>
<p class="endtd"></p>
</td></tr>
<tr>
<th colspan="2">Const Method with Call Type in a Class Template </th></tr>
<tr>
<td>Old </td><td><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a73aa181fb48e360fd18f1c2b7d9073b0">MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</a></code>  </td></tr>
<tr>
<td>New </td><td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code>  </td></tr>
</table>
<h2><a class="anchor" id="NiceStrictNaggy"></a>
The Nice, the Strict, and the Naggy</h2>
<p>If a mock method has no <code>EXPECT_CALL</code> spec but is called, we say that it's an "uninteresting call", and the default action (which can be specified using <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code>) of the method will be taken. Currently, an uninteresting call will also by default cause gMock to print a warning. (In the future, we might remove this warning by default.)</p>
<p>However, sometimes you may want to ignore these uninteresting calls, and sometimes you may want to treat them as errors. gMock lets you make the decision on a per-mock-object basis.</p>
<p>Suppose your test uses a mock class <code>MockFoo</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(...) {</div>
<div class="line">  MockFoo mock_foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_foo, DoThis());</div>
<div class="line">  ... code that uses mock_foo ...</div>
<div class="line">}</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_ab5540a6d621853916be8240ff51819cf"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a></div><div class="ttdeci">#define TEST(test_suite_name, test_name)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:2334</div></div>
</div><!-- fragment --><p>If a method of <code>mock_foo</code> other than <code>DoThis()</code> is called, you will get a warning. However, if you rewrite your test to use <code>NiceMock&lt;MockFoo&gt;</code> instead, you can suppress the warning:</p>
<div class="fragment"><div class="line">using ::testing::NiceMock;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(...) {</div>
<div class="line">  NiceMock&lt;MockFoo&gt; mock_foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_foo, DoThis());</div>
<div class="line">  ... code that uses mock_foo ...</div>
<div class="line">}</div>
</div><!-- fragment --><p><code>NiceMock&lt;MockFoo&gt;</code> is a subclass of <code>MockFoo</code>, so it can be used wherever <code>MockFoo</code> is accepted.</p>
<p>It also works if <code>MockFoo</code>'s constructor takes some arguments, as <code>NiceMock&lt;MockFoo&gt;</code> "inherits" <code>MockFoo</code>'s constructors:</p>
<div class="fragment"><div class="line">using ::testing::NiceMock;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(...) {</div>
<div class="line">  NiceMock&lt;MockFoo&gt; mock_foo(5, <span class="stringliteral">&quot;hi&quot;</span>);  <span class="comment">// Calls MockFoo(5, &quot;hi&quot;).</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_foo, DoThis());</div>
<div class="line">  ... code that uses mock_foo ...</div>
<div class="line">}</div>
</div><!-- fragment --><p>The usage of <code>StrictMock</code> is similar, except that it makes all uninteresting calls failures:</p>
<div class="fragment"><div class="line">using ::testing::StrictMock;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(...) {</div>
<div class="line">  StrictMock&lt;MockFoo&gt; mock_foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_foo, DoThis());</div>
<div class="line">  ... code that uses mock_foo ...</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The test will fail if a method of mock_foo other than DoThis()</span></div>
<div class="line">  <span class="comment">// is called.</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>{: .callout .note} NOTE: <code>NiceMock</code> and <code>StrictMock</code> only affects <em>uninteresting</em> calls (calls of <em>methods</em> with no expectations); they do not affect <em>unexpected</em> calls (calls of methods with expectations, but they don't match). See <a href="#uninteresting-vs-unexpected">Understanding Uninteresting vs Unexpected Calls</a>.</p>
<p>There are some caveats though (sadly they are side effects of C++'s limitations):</p>
<ol type="1">
<li><code>NiceMock&lt;MockFoo&gt;</code> and <code>StrictMock&lt;MockFoo&gt;</code> only work for mock methods defined using the <code>MOCK_METHOD</code> macro <b>directly</b> in the <code>MockFoo</code> class. If a mock method is defined in a <b>base class</b> of <code>MockFoo</code>, the "nice" or "strict" modifier may not affect it, depending on the compiler. In particular, nesting <code>NiceMock</code> and <code>StrictMock</code> (e.g. <code>NiceMock&lt;StrictMock&lt;MockFoo&gt; &gt;</code>) is <b>not</b> supported.</li>
<li><code>NiceMock&lt;MockFoo&gt;</code> and <code>StrictMock&lt;MockFoo&gt;</code> may not work correctly if the destructor of <code>MockFoo</code> is not virtual. We would like to fix this, but it requires cleaning up existing tests.</li>
</ol>
<p>Finally, you should be <b>very cautious</b> about when to use naggy or strict mocks, as they tend to make tests more brittle and harder to maintain. When you refactor your code without changing its externally visible behavior, ideally you shouldn't need to update any tests. If your code interacts with a naggy mock, however, you may start to get spammed with warnings as the result of your change. Worse, if your code interacts with a strict mock, your tests may start to fail and you'll be forced to fix them. Our general recommendation is to use nice mocks (not yet the default) most of the time, use naggy mocks (the current default) when developing or debugging tests, and use strict mocks only as the last resort.</p>
<h2><a class="anchor" id="SimplerInterfaces"></a>
Simplifying the Interface without Breaking Existing Code</h2>
<p>Sometimes a method has a long list of arguments that is mostly uninteresting. For example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>LogSink {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> send(<a class="code" href="namespacetesting_1_1internal.html#a203d1a8a2147a53d12bbdae40d443914">LogSeverity</a> severity, <span class="keyword">const</span> <span class="keywordtype">char</span>* full_filename,</div>
<div class="line">                    <span class="keyword">const</span> <span class="keywordtype">char</span>* base_filename, <span class="keywordtype">int</span> line,</div>
<div class="line">                    <span class="keyword">const</span> <span class="keyword">struct</span> tm* tm_time,</div>
<div class="line">                    <span class="keyword">const</span> <span class="keywordtype">char</span>* message, <span class="keywordtype">size_t</span> message_len) = 0;</div>
<div class="line">};</div>
<div class="ttc" id="anamespacetesting_1_1internal_html_a203d1a8a2147a53d12bbdae40d443914"><div class="ttname"><a href="namespacetesting_1_1internal.html#a203d1a8a2147a53d12bbdae40d443914">testing::internal::LogSeverity</a></div><div class="ttdeci">LogSeverity</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/internal/gmock-internal-utils.h:240</div></div>
</div><!-- fragment --><p>This method's argument list is lengthy and hard to work with (the <code>message</code> argument is not even 0-terminated). If we mock it as is, using the mock will be awkward. If, however, we try to simplify this interface, we'll need to fix all clients depending on it, which is often infeasible.</p>
<p>The trick is to redispatch the method in the mock class:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>ScopedMockLog : <span class="keyword">public</span> LogSink {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> send(<a class="code" href="namespacetesting_1_1internal.html#a203d1a8a2147a53d12bbdae40d443914">LogSeverity</a> severity, <span class="keyword">const</span> <span class="keywordtype">char</span>* full_filename,</div>
<div class="line">                    <span class="keyword">const</span> <span class="keywordtype">char</span>* base_filename, <span class="keywordtype">int</span> line, <span class="keyword">const</span> tm* tm_time,</div>
<div class="line">                    <span class="keyword">const</span> <span class="keywordtype">char</span>* message, <span class="keywordtype">size_t</span> message_len) {</div>
<div class="line">    <span class="comment">// We are only interested in the log severity, full file name, and</span></div>
<div class="line">    <span class="comment">// log message.</span></div>
<div class="line">    <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(severity, full_filename, std::string(message, message_len));</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Implements the mock method:</span></div>
<div class="line">  <span class="comment">//</span></div>
<div class="line">  <span class="comment">//   void Log(LogSeverity severity,</span></div>
<div class="line">  <span class="comment">//            const string&amp; file_path,</span></div>
<div class="line">  <span class="comment">//            const string&amp; message);</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>,</div>
<div class="line">              (<a class="code" href="namespacetesting_1_1internal.html#a203d1a8a2147a53d12bbdae40d443914">LogSeverity</a> severity, <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; file_path,</div>
<div class="line">               <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; message));</div>
<div class="line">};</div>
<div class="ttc" id="anamespacetesting_1_1internal_html_a8a57ce0412334a3f487bbaa8321febbe"><div class="ttname"><a href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">testing::internal::Log</a></div><div class="ttdeci">GTEST_API_ void Log(LogSeverity severity, const std::string &amp;message, int stack_frames_to_skip)</div></div>
</div><!-- fragment --><p>By defining a new mock method with a trimmed argument list, we make the mock class more user-friendly.</p>
<p>This technique may also be applied to make overloaded methods more amenable to mocking. For example, when overloads have been used to implement default arguments:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockTurtleFactory : <span class="keyword">public</span> TurtleFactory {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  Turtle* MakeTurtle(<span class="keywordtype">int</span> length, <span class="keywordtype">int</span> weight)<span class="keyword"> override </span>{ ... }</div>
<div class="line">  Turtle* MakeTurtle(<span class="keywordtype">int</span> length, <span class="keywordtype">int</span> weight, <span class="keywordtype">int</span> speed)<span class="keyword"> override </span>{ ... }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// the above methods delegate to this one:</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(Turtle*, DoMakeTurtle, ());</div>
<div class="line">};</div>
</div><!-- fragment --><p>This allows tests that don't care which overload was invoked to avoid specifying argument matchers:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(factory, DoMakeTurtle)</div>
<div class="line">    .WillByDefault(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(MakeMockTurtle()));</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h_html_a5b12ae6cf84f0a544ca811b380c37334"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a></div><div class="ttdeci">#define ON_CALL(obj, call)</div></div>
<div class="ttc" id="anamespacetesting_html_adae3994eb444d1ad2dd602454b854663"><div class="ttname"><a href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">testing::Return</a></div><div class="ttdeci">internal::ReturnAction&lt; R &gt; Return(R value)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1244</div></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md141"></a>
Alternative to Mocking Concrete Classes</h2>
<p>Often you may find yourself using classes that don't implement interfaces. In order to test your code that uses such a class (let's call it <code>Concrete</code>), you may be tempted to make the methods of <code>Concrete</code> virtual and then mock it.</p>
<p>Try not to do that.</p>
<p>Making a non-virtual function virtual is a big decision. It creates an extension point where subclasses can tweak your class' behavior. This weakens your control on the class because now it's harder to maintain the class invariants. You should make a function virtual only when there is a valid reason for a subclass to override it.</p>
<p>Mocking concrete classes directly is problematic as it creates a tight coupling between the class and the tests - any small change in the class may invalidate your tests and make test maintenance a pain.</p>
<p>To avoid such problems, many programmers have been practicing "coding to
interfaces": instead of talking to the <code>Concrete</code> class, your code would define an interface and talk to it. Then you implement that interface as an adaptor on top of <code>Concrete</code>. In tests, you can easily mock that interface to observe how your code is doing.</p>
<p>This technique incurs some overhead:</p>
<ul>
<li>You pay the cost of virtual function calls (usually not a problem).</li>
<li>There is more abstraction for the programmers to learn.</li>
</ul>
<p>However, it can also bring significant benefits in addition to better testability:</p>
<ul>
<li><code>Concrete</code>'s API may not fit your problem domain very well, as you may not be the only client it tries to serve. By designing your own interface, you have a chance to tailor it to your need - you may add higher-level functionalities, rename stuff, etc instead of just trimming the class. This allows you to write your code (user of the interface) in a more natural way, which means it will be more readable, more maintainable, and you'll be more productive.</li>
<li>If <code>Concrete</code>'s implementation ever has to change, you don't have to rewrite everywhere it is used. Instead, you can absorb the change in your implementation of the interface, and your other code and tests will be insulated from this change.</li>
</ul>
<p>Some people worry that if everyone is practicing this technique, they will end up writing lots of redundant code. This concern is totally understandable. However, there are two reasons why it may not be the case:</p>
<ul>
<li>Different projects may need to use <code>Concrete</code> in different ways, so the best interfaces for them will be different. Therefore, each of them will have its own domain-specific interface on top of <code>Concrete</code>, and they will not be the same code.</li>
<li>If enough projects want to use the same interface, they can always share it, just like they have been sharing <code>Concrete</code>. You can check in the interface and the adaptor somewhere near <code>Concrete</code> (perhaps in a <code>contrib</code> sub-directory) and let many projects use it.</li>
</ul>
<p>You need to weigh the pros and cons carefully for your particular problem, but I'd like to assure you that the Java community has been practicing this for a long time and it's a proven effective technique applicable in a wide variety of situations. :-)</p>
<h2><a class="anchor" id="DelegatingToFake"></a>
Delegating Calls to a Fake</h2>
<p>Some times you have a non-trivial fake implementation of an interface. For example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~Foo() {}</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">char</span> DoThis(<span class="keywordtype">int</span> n) = 0;</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> DoThat(<span class="keyword">const</span> <span class="keywordtype">char</span>* s, <span class="keywordtype">int</span>* p) = 0;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>FakeFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">char</span> DoThis(<span class="keywordtype">int</span> n)<span class="keyword"> override </span>{</div>
<div class="line">    <span class="keywordflow">return</span> (n &gt; 0) ? <span class="charliteral">&#39;+&#39;</span> :</div>
<div class="line">           (n &lt; 0) ? <span class="charliteral">&#39;-&#39;</span> : <span class="charliteral">&#39;0&#39;</span>;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DoThat(<span class="keyword">const</span> <span class="keywordtype">char</span>* s, <span class="keywordtype">int</span>* p)<span class="keyword"> override </span>{</div>
<div class="line">    *p = strlen(s);</div>
<div class="line">  }</div>
<div class="line">};</div>
</div><!-- fragment --><p>Now you want to mock this interface such that you can set expectations on it. However, you also want to use <code>FakeFoo</code> for the default behavior, as duplicating it in the mock object is, well, a lot of work.</p>
<p>When you define the mock class using gMock, you can have it delegate its default action to a fake class you already have, using this pattern:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// Normal mock method definitions using gMock.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">char</span>, DoThis, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, DoThat, (<span class="keyword">const</span> <span class="keywordtype">char</span>* s, <span class="keywordtype">int</span>* p), (<span class="keyword">override</span>));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Delegates the default actions of the methods to a FakeFoo object.</span></div>
<div class="line">  <span class="comment">// This must be called *before* the custom ON_CALL() statements.</span></div>
<div class="line">  <span class="keywordtype">void</span> DelegateToFake() {</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(*<span class="keyword">this</span>, DoThis).WillByDefault([<span class="keyword">this</span>](<span class="keywordtype">int</span> n) {</div>
<div class="line">      <span class="keywordflow">return</span> fake_.DoThis(n);</div>
<div class="line">    });</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(*<span class="keyword">this</span>, DoThat).WillByDefault([<span class="keyword">this</span>](<span class="keyword">const</span> <span class="keywordtype">char</span>* s, <span class="keywordtype">int</span>* p) {</div>
<div class="line">      fake_.DoThat(s, p);</div>
<div class="line">    });</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line"> <span class="keyword">private</span>:</div>
<div class="line">  FakeFoo fake_;  <span class="comment">// Keeps an instance of the fake in the mock.</span></div>
<div class="line">};</div>
</div><!-- fragment --><p>With that, you can use <code>MockFoo</code> in your tests as usual. Just remember that if you don't explicitly set an action in an <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> or <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>, the fake will be called upon to do it.:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(AbcTest, Xyz) {</div>
<div class="line">  MockFoo foo;</div>
<div class="line"> </div>
<div class="line">  foo.DelegateToFake();  <span class="comment">// Enables the fake for delegation.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Put your ON_CALL(foo, ...)s here, if any.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// No action specified, meaning to use the default action.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(5));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat(_, _));</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">int</span> n = 0;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(<span class="charliteral">&#39;+&#39;</span>, foo.DoThis(5));  <span class="comment">// FakeFoo::DoThis() is invoked.</span></div>
<div class="line">  foo.DoThat(<span class="stringliteral">&quot;Hi&quot;</span>, &amp;n);  <span class="comment">// FakeFoo::DoThat() is invoked.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(2, n);</div>
<div class="line">}</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_a4159019abda84f5366acdb7604ff220a"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a></div><div class="ttdeci">#define EXPECT_EQ(val1, val2)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:2024</div></div>
</div><!-- fragment --><p><b>Some tips:</b></p>
<ul>
<li>If you want, you can still override the default action by providing your own <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> or using <code>.WillOnce()</code> / <code>.WillRepeatedly()</code> in <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>.</li>
<li>In <code>DelegateToFake()</code>, you only need to delegate the methods whose fake implementation you intend to use.</li>
<li>The general technique discussed here works for overloaded methods, but you'll need to tell the compiler which version you mean. To disambiguate a mock function (the one you specify inside the parentheses of <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code>), use <a href="#SelectOverload">this technique</a>; to disambiguate a fake function (the one you place inside <code><a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke()</a></code>), use a <code>static_cast</code> to specify the function's type. For instance, if class <code>Foo</code> has methods <code>char DoThis(int n)</code> and <code>bool DoThis(double x) const</code>, and you want to invoke the latter, you need to write <code>Invoke(&amp;fake_, static_cast&lt;bool (FakeFoo::*)(double) const&gt;(&amp;FakeFoo::DoThis))</code> instead of <code>Invoke(&amp;fake_, &amp;FakeFoo::DoThis)</code> (The strange-looking thing inside the angled brackets of <code>static_cast</code> is the type of a function pointer to the second <code>DoThis()</code> method.).</li>
<li>Having to mix a mock and a fake is often a sign of something gone wrong. Perhaps you haven't got used to the interaction-based way of testing yet. Or perhaps your interface is taking on too many roles and should be split up. Therefore, <b>don't abuse this</b>. We would only recommend to do it as an intermediate step when you are refactoring your code.</li>
</ul>
<p>Regarding the tip on mixing a mock and a fake, here's an example on why it may be a bad sign: Suppose you have a class <code>System</code> for low-level system operations. In particular, it does file and I/O operations. And suppose you want to test how your code uses <code>System</code> to do I/O, and you just want the file operations to work normally. If you mock out the entire <code>System</code> class, you'll have to provide a fake implementation for the file operation part, which suggests that <code>System</code> is taking on too many roles.</p>
<p>Instead, you can define a <code>FileOps</code> interface and an <code>IOOps</code> interface and split <code>System</code>'s functionalities into the two. Then you can mock <code>IOOps</code> without mocking <code>FileOps</code>.</p>
<h2><a class="anchor" id="autotoc_md142"></a>
Delegating Calls to a Real Object</h2>
<p>When using testing doubles (mocks, fakes, stubs, and etc), sometimes their behaviors will differ from those of the real objects. This difference could be either intentional (as in simulating an error such that you can test the error handling code) or unintentional. If your mocks have different behaviors than the real objects by mistake, you could end up with code that passes the tests but fails in production.</p>
<p>You can use the <em>delegating-to-real</em> technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. This technique is very similar to the <a href="#DelegatingToFake">delegating-to-fake</a> technique, the difference being that we use a real object instead of a fake. Here's an example:</p>
<div class="fragment"><div class="line">using ::testing::AtLeast;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  MockFoo() {</div>
<div class="line">    <span class="comment">// By default, all calls are delegated to the real object.</span></div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(*<span class="keyword">this</span>, DoThis).WillByDefault([<span class="keyword">this</span>](<span class="keywordtype">int</span> n) {</div>
<div class="line">      <span class="keywordflow">return</span> real_.DoThis(n);</div>
<div class="line">    });</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(*<span class="keyword">this</span>, DoThat).WillByDefault([<span class="keyword">this</span>](<span class="keyword">const</span> <span class="keywordtype">char</span>* s, <span class="keywordtype">int</span>* p) {</div>
<div class="line">      real_.DoThat(s, p);</div>
<div class="line">    });</div>
<div class="line">    ...</div>
<div class="line">  }</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">char</span>, DoThis, ...);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, DoThat, ...);</div>
<div class="line">  ...</div>
<div class="line"> <span class="keyword">private</span>:</div>
<div class="line">  Foo real_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  MockFoo mock;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, DoThis())</div>
<div class="line">      .Times(3);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, DoThat(<span class="stringliteral">&quot;Hi&quot;</span>))</div>
<div class="line">      .Times(AtLeast(1));</div>
<div class="line">  ... use mock in test ...</div>
</div><!-- fragment --><p>With this, gMock will verify that your code made the right calls (with the right arguments, in the right order, called the right number of times, etc), and a real object will answer the calls (so the behavior will be the same as in production). This gives you the best of both worlds.</p>
<h2><a class="anchor" id="autotoc_md143"></a>
Delegating Calls to a Parent Class</h2>
<p>Ideally, you should code to interfaces, whose methods are all pure virtual. In reality, sometimes you do need to mock a virtual method that is not pure (i.e, it already has an implementation). For example:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~Foo();</div>
<div class="line"> </div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> Pure(<span class="keywordtype">int</span> n) = 0;</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">int</span> Concrete(<span class="keyword">const</span> <span class="keywordtype">char</span>* str) { ... }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// Mocking a pure method.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Pure, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">  <span class="comment">// Mocking a concrete method.  Foo::Concrete() is shadowed.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, Concrete, (<span class="keyword">const</span> <span class="keywordtype">char</span>* str), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><p>Sometimes you may want to call <code>Foo::Concrete()</code> instead of <code>MockFoo::Concrete()</code>. Perhaps you want to do it as part of a stub action, or perhaps your test doesn't need to mock <code>Concrete()</code> at all (but it would be oh-so painful to have to define a new mock class whenever you don't need to mock one of its methods).</p>
<p>You can call <code>Foo::Concrete()</code> inside an action by:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Concrete).WillOnce([&amp;foo](<span class="keyword">const</span> <span class="keywordtype">char</span>* str) {</div>
<div class="line">    <span class="keywordflow">return</span> foo.Foo::Concrete(str);</div>
<div class="line">  });</div>
</div><!-- fragment --><p>or tell the mock object that you don't want to mock <code>Concrete()</code>:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(foo, Concrete).WillByDefault([&amp;foo](<span class="keyword">const</span> <span class="keywordtype">char</span>* str) {</div>
<div class="line">    <span class="keywordflow">return</span> foo.Foo::Concrete(str);</div>
<div class="line">  });</div>
</div><!-- fragment --><p>(Why don't we just write <code>{ return foo.Concrete(str); }</code>? If you do that, <code>MockFoo::Concrete()</code> will be called (and cause an infinite recursion) since <code>Foo::Concrete()</code> is virtual. That's just how C++ works.)</p>
<h1><a class="anchor" id="autotoc_md144"></a>
Using Matchers</h1>
<h2><a class="anchor" id="autotoc_md145"></a>
Matching Argument Values Exactly</h2>
<p>You can specify exactly which arguments a mock method is expecting:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(5))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="charliteral">&#39;a&#39;</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat(<span class="stringliteral">&quot;Hello&quot;</span>, bar));</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md146"></a>
Using Simple Matchers</h2>
<p>You can use matchers to match arguments that have a certain property:</p>
<div class="fragment"><div class="line">using ::testing::NotNull;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(Ge(5)))  <span class="comment">// The argument must be &gt;= 5.</span></div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="charliteral">&#39;a&#39;</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat(<span class="stringliteral">&quot;Hello&quot;</span>, NotNull()));</div>
<div class="line">      <span class="comment">// The second argument must not be NULL.</span></div>
</div><!-- fragment --><p>A frequently used matcher is <code>_</code>, which matches anything:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat(_, NotNull()));</div>
</div><!-- fragment --><h2><a class="anchor" id="CombiningMatchers"></a>
Combining Matchers</h2>
<p>You can build complex matchers from existing ones using <code>AllOf()</code>, <code>AllOfArray()</code>, <code>AnyOf()</code>, <code>AnyOfArray()</code> and <code>Not()</code>:</p>
<div class="fragment"><div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line">using ::testing::HasSubstr;</div>
<div class="line">using ::testing::Ne;</div>
<div class="line">using ::testing::Not;</div>
<div class="line">...</div>
<div class="line">  <span class="comment">// The argument must be &gt; 5 and != 10.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(AllOf(Gt(5),</div>
<div class="line">                                Ne(10))));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// The first argument must not contain sub-string &quot;blah&quot;.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat(Not(HasSubstr(<span class="stringliteral">&quot;blah&quot;</span>)),</div>
<div class="line">                          NULL));</div>
</div><!-- fragment --><p>Matchers are function objects, and parametrized matchers can be composed just like any other function. However because their types can be long and rarely provide meaningful information, it can be easier to express them with C++14 generic lambdas to avoid specifying types. For example,</p>
<div class="fragment"><div class="line">using ::testing::Contains;</div>
<div class="line">using ::testing::Property;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">inline</span> constexpr <span class="keyword">auto</span> HasFoo = [](<span class="keyword">const</span> <span class="keyword">auto</span>&amp; f) {</div>
<div class="line">  <span class="keywordflow">return</span> Property(&amp;MyClass::foo, Contains(f));</div>
<div class="line">};</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(x, HasFoo(<span class="stringliteral">&quot;blah&quot;</span>));</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h_html_ac31e206123aa702e1152bb2735b31409"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a></div><div class="ttdeci">#define EXPECT_THAT(value, matcher)</div></div>
</div><!-- fragment --><h2><a class="anchor" id="SafeMatcherCast"></a>
Casting Matchers</h2>
<p>gMock matchers are statically typed, meaning that the compiler can catch your mistake if you use a matcher of the wrong type (for example, if you use <code>Eq(5)</code> to match a <code>string</code> argument). Good for you!</p>
<p>Sometimes, however, you know what you're doing and want the compiler to give you some slack. One example is that you have a matcher for <code>long</code> and the argument you want to match is <code>int</code>. While the two types aren't exactly the same, there is nothing really wrong with using a <code>Matcher&lt;long&gt;</code> to match an <code>int</code> - after all, we can first convert the <code>int</code> argument to a <code>long</code> losslessly before giving it to the matcher.</p>
<p>To support this need, gMock gives you the <code>SafeMatcherCast&lt;T&gt;(m)</code> function. It casts a matcher <code>m</code> to type <code>Matcher&lt;T&gt;</code>. To ensure safety, gMock checks that (let <code>U</code> be the type <code>m</code> accepts :</p>
<ol type="1">
<li>Type <code>T</code> can be <em>implicitly</em> cast to type <code>U</code>;</li>
<li>When both <code>T</code> and <code>U</code> are built-in arithmetic types (<code>bool</code>, integers, and floating-point numbers), the conversion from <code>T</code> to <code>U</code> is not lossy (in other words, any value representable by <code>T</code> can also be represented by <code>U</code>); and</li>
<li>When <code>U</code> is a reference, <code>T</code> must also be a reference (as the underlying matcher may be interested in the address of the <code>U</code> value).</li>
</ol>
<p>The code won't compile if any of these conditions isn't met.</p>
<p>Here's one example:</p>
<div class="fragment"><div class="line">using ::testing::SafeMatcherCast;</div>
<div class="line"> </div>
<div class="line"><span class="comment">// A base class and a child class.</span></div>
<div class="line"><span class="keyword">class </span>Base { ... };</div>
<div class="line"><span class="keyword">class </span>Derived : <span class="keyword">public</span> Base { ... };</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, DoThis, (Derived* derived), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <span class="comment">// m is a Matcher&lt;Base*&gt; we got from somewhere.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(SafeMatcherCast&lt;Derived*&gt;(m)));</div>
</div><!-- fragment --><p>If you find <code>SafeMatcherCast&lt;T&gt;(m)</code> too limiting, you can use a similar function <code>MatcherCast&lt;T&gt;(m)</code>. The difference is that <code>MatcherCast</code> works as long as you can <code>static_cast</code> type <code>T</code> to type <code>U</code>.</p>
<p><code>MatcherCast</code> essentially lets you bypass C++'s type system (<code>static_cast</code> isn't always safe as it could throw away information, for example), so be careful not to misuse/abuse it.</p>
<h2><a class="anchor" id="SelectOverload"></a>
Selecting Between Overloaded Functions</h2>
<p>If you expect an overloaded function to be called, the compiler may need some help on which overloaded version it is.</p>
<p>To disambiguate functions overloaded on the const-ness of this object, use the <code>Const()</code> argument wrapper.</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">using ::testing::ReturnRef</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line">  ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(Bar&amp;, GetBar, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keyword">const</span> Bar&amp;, GetBar, (), (<span class="keyword">const</span>, <span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  Bar bar1, bar2;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, GetBar())         <span class="comment">// The non-const GetBar().</span></div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef</a>(bar1));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(Const(foo), GetBar())  <span class="comment">// The const GetBar().</span></div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef</a>(bar2));</div>
<div class="ttc" id="anamespacetesting_html_ac17089d5ca6377944d3792fbdc5c5d9b"><div class="ttname"><a href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">testing::ReturnRef</a></div><div class="ttdeci">internal::ReturnRefAction&lt; R &gt; ReturnRef(R &amp;x)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1260</div></div>
</div><!-- fragment --><p>(<code>Const()</code> is defined by gMock and returns a <code>const</code> reference to its argument.)</p>
<p>To disambiguate overloaded functions with the same number of arguments but different argument types, you may need to specify the exact type of a matcher, either by wrapping your matcher in <code>Matcher&lt;type&gt;()</code>, or using a matcher whose type is fixed (<code>TypedEq&lt;type&gt;</code>, <code>An&lt;type&gt;()</code>, etc):</p>
<div class="fragment"><div class="line">using ::testing::An;</div>
<div class="line">using ::testing::Matcher;</div>
<div class="line">using ::testing::TypedEq;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockPrinter : <span class="keyword">public</span> Printer {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Print, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Print, (<span class="keywordtype">char</span> c), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(PrinterTest, Print) {</div>
<div class="line">  MockPrinter printer;</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(printer, Print(An&lt;int&gt;()));            <span class="comment">// void Print(int);</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(printer, Print(Matcher&lt;int&gt;(Lt(5))));  <span class="comment">// void Print(int);</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(printer, Print(TypedEq&lt;char&gt;(<span class="charliteral">&#39;a&#39;</span>)));   <span class="comment">// void Print(char);</span></div>
<div class="line"> </div>
<div class="line">  printer.Print(3);</div>
<div class="line">  printer.Print(6);</div>
<div class="line">  printer.Print(<span class="charliteral">&#39;a&#39;</span>);</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md147"></a>
Performing Different Actions Based on the Arguments</h2>
<p>When a mock method is called, the <em>last</em> matching expectation that's still active will be selected (think "newer overrides older"). So, you can make a method do different things depending on its argument values like this:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::Lt;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line">...</div>
<div class="line">  <span class="comment">// The default case.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(_))</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="charliteral">&#39;b&#39;</span>));</div>
<div class="line">  <span class="comment">// The more specific case.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(Lt(5)))</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="charliteral">&#39;a&#39;</span>));</div>
</div><!-- fragment --><p>Now, if <code>foo.DoThis()</code> is called with a value less than 5, &lsquo;'a&rsquo;<code>will be returned; otherwise</code>'b'` will be returned.</p>
<h2><a class="anchor" id="autotoc_md148"></a>
Matching Multiple Arguments as a Whole</h2>
<p>Sometimes it's not enough to match the arguments individually. For example, we may want to say that the first argument must be less than the second argument. The <code>With()</code> clause allows us to match all arguments of a mock function as a whole. For example,</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::Ne;</div>
<div class="line">using ::testing::Lt;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, InRange(Ne(0), _))</div>
<div class="line">      .With(Lt());</div>
</div><!-- fragment --><p>says that the first argument of <code>InRange()</code> must not be 0, and must be less than the second argument.</p>
<p>The expression inside <code>With()</code> must be a matcher of type <code>Matcher&lt;std::tuple&lt;A1, ..., An&gt;&gt;</code>, where <code>A1</code>, ..., <code>An</code> are the types of the function arguments.</p>
<p>You can also write <code>AllArgs(m)</code> instead of <code>m</code> inside <code>.With()</code>. The two forms are equivalent, but <code>.With(AllArgs(Lt()))</code> is more readable than <code>.With(Lt())</code>.</p>
<p>You can use <code>Args&lt;k1, ..., kn&gt;(m)</code> to match the <code>n</code> selected arguments (as a tuple) against <code>m</code>. For example,</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::Args;</div>
<div class="line">using ::testing::Lt;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Blah)</div>
<div class="line">      .With(AllOf(Args&lt;0, 1&gt;(Lt()), Args&lt;1, 2&gt;(Lt())));</div>
</div><!-- fragment --><p>says that <code>Blah</code> will be called with arguments <code>x</code>, <code>y</code>, and <code>z</code> where <code>x &lt; y &lt; z</code>. Note that in this example, it wasn't necessary specify the positional matchers.</p>
<p>As a convenience and example, gMock provides some matchers for 2-tuples, including the <code>Lt()</code> matcher above. See <a href="#MultiArgMatchers">here</a> for the complete list.</p>
<p>Note that if you want to pass the arguments to a predicate of your own (e.g. <code>.With(Args&lt;0, 1&gt;(Truly(&amp;MyPredicate)))</code>), that predicate MUST be written to take a <code>std::tuple</code> as its argument; gMock will pass the <code>n</code> selected arguments as <em>one</em> single tuple to the predicate.</p>
<h2><a class="anchor" id="autotoc_md149"></a>
Using Matchers as Predicates</h2>
<p>Have you noticed that a matcher is just a fancy predicate that also knows how to describe itself? Many existing algorithms take predicates as arguments (e.g. those defined in STL's <code>&lt;algorithm&gt;</code> header), and it would be a shame if gMock matchers were not allowed to participate.</p>
<p>Luckily, you can use a matcher where a unary predicate functor is expected by wrapping it inside the <code>Matches()</code> function. For example,</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;algorithm&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;vector&gt;</span></div>
<div class="line"> </div>
<div class="line">using ::testing::Matches;</div>
<div class="line">using ::testing::Ge;</div>
<div class="line"> </div>
<div class="line">vector&lt;int&gt; v;</div>
<div class="line">...</div>
<div class="line"><span class="comment">// How many elements in v are &gt;= 10?</span></div>
<div class="line">const <span class="keywordtype">int</span> count = count_if(v.begin(), v.end(), Matches(Ge(10)));</div>
</div><!-- fragment --><p>Since you can build complex matchers from simpler ones easily using gMock, this gives you a way to conveniently construct composite predicates (doing the same using STL's <code>&lt;functional&gt;</code> header is just painful). For example, here's a predicate that's satisfied by any number that is &gt;= 0, &lt;= 100, and != 50:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> testing::AllOf;</div>
<div class="line"><span class="keyword">using</span> testing::Ge;</div>
<div class="line"><span class="keyword">using</span> testing::Le;</div>
<div class="line"><span class="keyword">using</span> testing::Matches;</div>
<div class="line"><span class="keyword">using</span> testing::Ne;</div>
<div class="line">...</div>
<div class="line">Matches(AllOf(Ge(0), Le(100), Ne(50)))</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md150"></a>
Using Matchers in googletest Assertions</h2>
<p>Since matchers are basically predicates that also know how to describe themselves, there is a way to take advantage of them in googletest assertions. It's called <code>ASSERT_THAT</code> and <code>EXPECT_THAT</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a41d888579850c16583baea33ee8d057e">ASSERT_THAT</a>(value, matcher);  <span class="comment">// Asserts that value matches matcher.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(value, matcher);  <span class="comment">// The non-fatal version.</span></div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h_html_a41d888579850c16583baea33ee8d057e"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a41d888579850c16583baea33ee8d057e">ASSERT_THAT</a></div><div class="ttdeci">#define ASSERT_THAT(value, matcher)</div></div>
</div><!-- fragment --><p>For example, in a googletest test you can write:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;gmock/gmock.h&quot;</span></div>
<div class="line"> </div>
<div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::Ge;</div>
<div class="line">using ::testing::Le;</div>
<div class="line">using ::testing::MatchesRegex;</div>
<div class="line">using ::testing::StartsWith;</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(Foo(), StartsWith(<span class="stringliteral">&quot;Hello&quot;</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(Bar(), MatchesRegex(<span class="stringliteral">&quot;Line \\d+&quot;</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a41d888579850c16583baea33ee8d057e">ASSERT_THAT</a>(Baz(), AllOf(Ge(5), Le(10)));</div>
</div><!-- fragment --><p>which (as you can probably guess) executes <code>Foo()</code>, <code>Bar()</code>, and <code>Baz()</code>, and verifies that:</p>
<ul>
<li><code>Foo()</code> returns a string that starts with <code>"Hello"</code>.</li>
<li><code>Bar()</code> returns a string that matches regular expression <code>"Line \\d+"</code>.</li>
<li><code>Baz()</code> returns a number in the range [5, 10].</li>
</ul>
<p>The nice thing about these macros is that <em>they read like English</em>. They generate informative messages too. For example, if the first <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT()</a></code> above fails, the message will be something like:</p>
<div class="fragment"><div class="line">Value of: Foo()</div>
<div class="line">  Actual: &quot;Hi, world!&quot;</div>
<div class="line">Expected: starts with &quot;Hello&quot;</div>
</div><!-- fragment --><p><b>Credit:</b> The idea of <code>(ASSERT|EXPECT)_THAT</code> was borrowed from Joe Walnes' Hamcrest project, which adds <code>assertThat()</code> to JUnit.</p>
<h2><a class="anchor" id="autotoc_md151"></a>
Using Predicates as Matchers</h2>
<p>gMock provides a <a href="gmock_cheat_sheet.md#MatcherList">built-in set</a> of matchers. In case you find them lacking, you can use an arbitrary unary predicate function or functor as a matcher - as long as the predicate accepts a value of the type you want. You do this by wrapping the predicate inside the <code>Truly()</code> function, for example:</p>
<div class="fragment"><div class="line">using ::testing::Truly;</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> IsEven(<span class="keywordtype">int</span> n) { <span class="keywordflow">return</span> (n % 2) == 0 ? 1 : 0; }</div>
<div class="line">...</div>
<div class="line">  <span class="comment">// Bar() must be called with an even number.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(Truly(IsEven)));</div>
</div><!-- fragment --><p>Note that the predicate function / functor doesn't have to return <code>bool</code>. It works as long as the return value can be used as the condition in in statement <code>if (condition) ...</code>.</p>
<h2><a class="anchor" id="autotoc_md152"></a>
Matching Arguments that Are Not Copyable</h2>
<p>When you do an <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL(mock_obj, Foo(bar))</a></code>, gMock saves away a copy of <code>bar</code>. When <code>Foo()</code> is called later, gMock compares the argument to <code>Foo()</code> with the saved copy of <code>bar</code>. This way, you don't need to worry about <code>bar</code> being modified or destroyed after the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> is executed. The same is true when you use matchers like <code>Eq(bar)</code>, <code>Le(bar)</code>, and so on.</p>
<p>But what if <code>bar</code> cannot be copied (i.e. has no copy constructor)? You could define your own matcher function or callback and use it with <code>Truly()</code>, as the previous couple of recipes have shown. Or, you may be able to get away from it if you can guarantee that <code>bar</code> won't be changed after the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> is executed. Just tell gMock that it should save a reference to <code>bar</code>, instead of a copy of it. Here's how:</p>
<div class="fragment"><div class="line">using ::testing::Eq;</div>
<div class="line">using ::testing::Lt;</div>
<div class="line">...</div>
<div class="line">  <span class="comment">// Expects that Foo()&#39;s argument == bar.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_obj, Foo(Eq(std::ref(bar))));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Expects that Foo()&#39;s argument &lt; bar.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_obj, Foo(Lt(std::ref(bar))));</div>
</div><!-- fragment --><p>Remember: if you do this, don't change <code>bar</code> after the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>, or the result is undefined.</p>
<h2><a class="anchor" id="autotoc_md153"></a>
Validating a Member of an Object</h2>
<p>Often a mock function takes a reference to object as an argument. When matching the argument, you may not want to compare the entire object against a fixed object, as that may be over-specification. Instead, you may need to validate a certain member variable or the result of a certain getter method of the object. You can do this with <code>Field()</code> and <code>Property()</code>. More specifically,</p>
<div class="fragment"><div class="line">Field(&amp;Foo::bar, m)</div>
</div><!-- fragment --><p>is a matcher that matches a <code>Foo</code> object whose <code>bar</code> member variable satisfies matcher <code>m</code>.</p>
<div class="fragment"><div class="line">Property(&amp;Foo::baz, m)</div>
</div><!-- fragment --><p>is a matcher that matches a <code>Foo</code> object whose <code>baz()</code> method returns a value that satisfies matcher <code>m</code>.</p>
<p>For example:</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadLeft">Expression   </th><th class="markdownTableHeadLeft">Description    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyLeft"><code>Field(&amp;Foo::number, Ge(3))</code>   </td><td class="markdownTableBodyLeft">Matches <code>x</code> where <code>x.number &gt;= 3</code>.    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyLeft"><code>Property(&amp;Foo::name, StartsWith("John "))</code>   </td><td class="markdownTableBodyLeft">Matches <code>x</code> where <code>x.name()</code> starts with <code>"John "</code>.   </td></tr>
</table>
<p>Note that in <code>Property(&amp;Foo::baz, ...)</code>, method <code>baz()</code> must take no argument and be declared as <code>const</code>. Don't use <code>Property()</code> against member functions that you do not own, because taking addresses of functions is fragile and generally not part of the contract of the function.</p>
<p><code>Field()</code> and <code>Property()</code> can also match plain pointers to objects. For instance,</p>
<div class="fragment"><div class="line">using ::testing::Field;</div>
<div class="line">using ::testing::Ge;</div>
<div class="line">...</div>
<div class="line">Field(&amp;Foo::number, Ge(3))</div>
</div><!-- fragment --><p>matches a plain pointer <code>p</code> where <code>p-&gt;number &gt;= 3</code>. If <code>p</code> is <code>NULL</code>, the match will always fail regardless of the inner matcher.</p>
<p>What if you want to validate more than one members at the same time? Remember that there are <a href="#CombiningMatchers"><code>AllOf()</code> and <code>AllOfArray()</code></a>.</p>
<p>Finally <code>Field()</code> and <code>Property()</code> provide overloads that take the field or property names as the first argument to include it in the error message. This can be useful when creating combined matchers.</p>
<div class="fragment"><div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::Field;</div>
<div class="line">using ::testing::Matcher;</div>
<div class="line">using ::testing::SafeMatcherCast;</div>
<div class="line"> </div>
<div class="line">Matcher&lt;Foo&gt; IsFoo(<span class="keyword">const</span> Foo&amp; foo) {</div>
<div class="line">  <span class="keywordflow">return</span> AllOf(Field(<span class="stringliteral">&quot;some_field&quot;</span>, &amp;Foo::some_field, foo.some_field),</div>
<div class="line">               Field(<span class="stringliteral">&quot;other_field&quot;</span>, &amp;Foo::other_field, foo.other_field),</div>
<div class="line">               Field(<span class="stringliteral">&quot;last_field&quot;</span>, &amp;Foo::last_field, foo.last_field));</div>
<div class="line">}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md154"></a>
Validating the Value Pointed to by a Pointer Argument</h2>
<p>C++ functions often take pointers as arguments. You can use matchers like <code>IsNull()</code>, <code>NotNull()</code>, and other comparison matchers to match a pointer, but what if you want to make sure the value <em>pointed to</em> by the pointer, instead of the pointer itself, has a certain property? Well, you can use the <code>Pointee(m)</code> matcher.</p>
<p><code>Pointee(m)</code> matches a pointer if and only if <code>m</code> matches the value the pointer points to. For example:</p>
<div class="fragment"><div class="line">using ::testing::Ge;</div>
<div class="line">using ::testing::Pointee;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(Pointee(Ge(3))));</div>
</div><!-- fragment --><p>expects <code>foo.Bar()</code> to be called with a pointer that points to a value greater than or equal to 3.</p>
<p>One nice thing about <code>Pointee()</code> is that it treats a <code>NULL</code> pointer as a match failure, so you can write <code>Pointee(m)</code> instead of</p>
<div class="fragment"><div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::NotNull;</div>
<div class="line">using ::testing::Pointee;</div>
<div class="line">...</div>
<div class="line">  AllOf(NotNull(), Pointee(m))</div>
</div><!-- fragment --><p>without worrying that a <code>NULL</code> pointer will crash your test.</p>
<p>Also, did we tell you that <code>Pointee()</code> works with both raw pointers <b>and</b> smart pointers (<code>std::unique_ptr</code>, <code>std::shared_ptr</code>, etc)?</p>
<p>What if you have a pointer to pointer? You guessed it - you can use nested <code>Pointee()</code> to probe deeper inside the value. For example, <code>Pointee(Pointee(Lt(3)))</code> matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...).</p>
<h2><a class="anchor" id="autotoc_md155"></a>
Testing a Certain Property of an Object</h2>
<p>Sometimes you want to specify that an object argument has a certain property, but there is no existing matcher that does this. If you want good error messages, you should <a href="#NewMatchers">define a matcher</a>. If you want to do it quick and dirty, you could get away with writing an ordinary function.</p>
<p>Let's say you have a mock function that takes an object of type <code>Foo</code>, which has an <code>int bar()</code> method and an <code>int baz()</code> method, and you want to constrain that the argument's <code>bar()</code> value plus its <code>baz()</code> value is a given number. Here's how you can define a matcher to do it:</p>
<div class="fragment"><div class="line">using ::testing::Matcher;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>BarPlusBazEqMatcher {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">explicit</span> BarPlusBazEqMatcher(<span class="keywordtype">int</span> expected_sum)</div>
<div class="line">      : expected_sum_(expected_sum) {}</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">bool</span> MatchAndExplain(<span class="keyword">const</span> Foo&amp; foo,</div>
<div class="line">                       std::ostream* <span class="comment">/* listener */</span>)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="keywordflow">return</span> (foo.bar() + foo.baz()) == expected_sum_;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DescribeTo(std::ostream&amp; os)<span class="keyword"> const </span>{</div>
<div class="line">    os &lt;&lt; <span class="stringliteral">&quot;bar() + baz() equals &quot;</span> &lt;&lt; expected_sum_;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DescribeNegationTo(std::ostream&amp; os)<span class="keyword"> const </span>{</div>
<div class="line">    os &lt;&lt; <span class="stringliteral">&quot;bar() + baz() does not equal &quot;</span> &lt;&lt; expected_sum_;</div>
<div class="line">  }</div>
<div class="line"> <span class="keyword">private</span>:</div>
<div class="line">  <span class="keyword">const</span> <span class="keywordtype">int</span> expected_sum_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">Matcher&lt;const Foo&amp;&gt; BarPlusBazEq(<span class="keywordtype">int</span> expected_sum) {</div>
<div class="line">  <span class="keywordflow">return</span> BarPlusBazEqMatcher(expected_sum);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(..., DoThis(BarPlusBazEq(5)))...;</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md156"></a>
Matching Containers</h2>
<p>Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock function and you may want to validate it. Since most STL containers support the <code>==</code> operator, you can write <code>Eq(expected_container)</code> or simply <code>expected_container</code> to match a container exactly.</p>
<p>Sometimes, though, you may want to be more flexible (for example, the first element must be an exact match, but the second element can be any positive number, and so on). Also, containers used in tests often have a small number of elements, and having to define the expected container out-of-line is a bit of a hassle.</p>
<p>You can use the <code>ElementsAre()</code> or <code>UnorderedElementsAre()</code> matcher in such cases:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::ElementsAre;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Foo, (<span class="keyword">const</span> vector&lt;int&gt;&amp; numbers), (<span class="keyword">override</span>));</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(ElementsAre(1, Gt(0), _, 5)));</div>
</div><!-- fragment --><p>The above matcher says that the container must have 4 elements, which must be 1, greater than 0, anything, and 5 respectively.</p>
<p>If you instead write:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line">using ::testing::UnorderedElementsAre;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Foo, (<span class="keyword">const</span> vector&lt;int&gt;&amp; numbers), (<span class="keyword">override</span>));</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));</div>
</div><!-- fragment --><p>It means that the container must have 4 elements, which (under some permutation) must be 1, greater than 0, anything, and 5 respectively.</p>
<p>As an alternative you can place the arguments in a C-style array and use <code>ElementsAreArray()</code> or <code>UnorderedElementsAreArray()</code> instead:</p>
<div class="fragment"><div class="line">using ::testing::ElementsAreArray;</div>
<div class="line">...</div>
<div class="line">  <span class="comment">// ElementsAreArray accepts an array of element values.</span></div>
<div class="line">  <span class="keyword">const</span> <span class="keywordtype">int</span> expected_vector1[] = {1, 5, 2, 4, ...};</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(ElementsAreArray(expected_vector1)));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Or, an array of element matchers.</span></div>
<div class="line">  Matcher&lt;int&gt; expected_vector2[] = {1, Gt(2), _, 3, ...};</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(ElementsAreArray(expected_vector2)));</div>
</div><!-- fragment --><p>In case the array needs to be dynamically created (and therefore the array size cannot be inferred by the compiler), you can give <code>ElementsAreArray()</code> an additional argument to specify the array size:</p>
<div class="fragment"><div class="line">using ::testing::ElementsAreArray;</div>
<div class="line">...</div>
<div class="line">  <span class="keywordtype">int</span>* <span class="keyword">const</span> expected_vector3 = <span class="keyword">new</span> <span class="keywordtype">int</span>[count];</div>
<div class="line">  ... fill expected_vector3 with values ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(ElementsAreArray(expected_vector3, count)));</div>
</div><!-- fragment --><p>Use <code>Pair</code> when comparing maps or other associative containers.</p>
<p>{% raw %}</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> testing::ElementsAre;</div>
<div class="line"><span class="keyword">using</span> testing::Pair;</div>
<div class="line">...</div>
<div class="line">  std::map&lt;string, int&gt; m = {{<span class="stringliteral">&quot;a&quot;</span>, 1}, {<span class="stringliteral">&quot;b&quot;</span>, 2}, {<span class="stringliteral">&quot;c&quot;</span>, 3}};</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(m, ElementsAre(Pair(<span class="stringliteral">&quot;a&quot;</span>, 1), Pair(<span class="stringliteral">&quot;b&quot;</span>, 2), Pair(<span class="stringliteral">&quot;c&quot;</span>, 3)));</div>
</div><!-- fragment --><p>{% endraw %}</p>
<p><b>Tips:</b></p>
<ul>
<li><code>ElementsAre*()</code> can be used to match <em>any</em> container that implements the STL iterator pattern (i.e. it has a <code>const_iterator</code> type and supports <code>begin()/end()</code>), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.</li>
<li>You can use nested <code>ElementsAre*()</code> to match nested (multi-dimensional) containers.</li>
<li>If the container is passed by pointer instead of by reference, just write <code>Pointee(ElementsAre*(...))</code>.</li>
<li>The order of elements <em>matters</em> for <code>ElementsAre*()</code>. If you are using it with containers whose element order are undefined (e.g. <code>hash_map</code>) you should use <code>WhenSorted</code> around <code>ElementsAre</code>.</li>
</ul>
<h2><a class="anchor" id="autotoc_md157"></a>
Sharing Matchers</h2>
<p>Under the hood, a gMock matcher object consists of a pointer to a ref-counted implementation object. Copying matchers is allowed and very efficient, as only the pointer is copied. When the last matcher that references the implementation object dies, the implementation object will be deleted.</p>
<p>Therefore, if you have some complex matcher that you want to use again and again, there is no need to build it everytime. Just assign it to a matcher variable and use that variable repeatedly! For example,</p>
<div class="fragment"><div class="line">using ::testing::AllOf;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line">using ::testing::Le;</div>
<div class="line">using ::testing::Matcher;</div>
<div class="line">...</div>
<div class="line">  Matcher&lt;int&gt; in_range = AllOf(Gt(5), Le(10));</div>
<div class="line">  ... use in_range as a matcher in multiple EXPECT_CALLs ...</div>
</div><!-- fragment --><h2><a class="anchor" id="PureMatchers"></a>
Matchers must have no side-effects</h2>
<p>{: .callout .warning} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be <em>purely functional</em>: they cannot have any side effects, and the match result must not depend on anything other than the matcher's parameters and the value being matched.</p>
<p>This requirement must be satisfied no matter how a matcher is defined (e.g., if it is one of the standard matchers, or a custom matcher). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and gMock.</p>
<h1><a class="anchor" id="autotoc_md158"></a>
Setting Expectations</h1>
<h2><a class="anchor" id="UseOnCall"></a>
Knowing When to Expect</h2>
<p>**<code>ON_CALL</code>** is likely the <em>single most under-utilized construct</em> in gMock.</p>
<p>There are basically two constructs for defining the behavior of a mock object: <code>ON_CALL</code> and <code>EXPECT_CALL</code>. The difference? <code>ON_CALL</code> defines what happens when a mock method is called, but <em>doesn't imply any expectation on the method being called</em>. <code>EXPECT_CALL</code> not only defines the behavior, but also sets an expectation that <em>the method will be called with the given arguments, for the given number of times</em> (and <em>in the given order</em> when you specify the order too).</p>
<p>Since <code>EXPECT_CALL</code> does more, isn't it better than <code>ON_CALL</code>? Not really. Every <code>EXPECT_CALL</code> adds a constraint on the behavior of the code under test. Having more constraints than necessary is <em>baaad</em> - even worse than not having enough constraints.</p>
<p>This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests?</p>
<p>The answer lies in <em>what</em> a test should verify. <b>A good test verifies the contract of the code.</b> If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed.</p>
<p>Keep in mind that one doesn't have to verify more than one property in one test. In fact, <b>it's a good style to verify only one thing in one test.</b> If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself.</p>
<p>So use <code>ON_CALL</code> by default, and only use <code>EXPECT_CALL</code> when you actually intend to verify that the call is made. For example, you may have a bunch of <code>ON_CALL</code>s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different <code>EXPECT_CALL</code>s in different <code>TEST_F</code>s to verify different aspects of the code's behavior. Compared with the style where each <code>TEST</code> has many <code>EXPECT_CALL</code>s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them).</p>
<p>If you are bothered by the "Uninteresting mock function call" message printed when a mock method without an <code>EXPECT_CALL</code> is called, you may use a <code>NiceMock</code> instead to suppress all such messages for the mock object, or suppress the message for specific methods by adding <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL(...)</a>.Times(AnyNumber())</code>. DO NOT suppress it by blindly adding an <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL(...)</a></code>, or you'll have a test that's a pain to maintain.</p>
<h2><a class="anchor" id="autotoc_md159"></a>
Ignoring Uninteresting Calls</h2>
<p>If you are not interested in how a mock method is called, just don't say anything about it. In this case, if the method is ever called, gMock will perform its default action to allow the test program to continue. If you are not happy with the default action taken by gMock, you can override it using <code>DefaultValue&lt;T&gt;::Set()</code> (described <a href="#DefaultValue">here</a>) or <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code>.</p>
<p>Please note that once you expressed interest in a particular mock method (via <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>), all invocations to it must match some expectation. If this function is called but the arguments don't match any <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statement, it will be an error.</p>
<h2><a class="anchor" id="autotoc_md160"></a>
Disallowing Unexpected Calls</h2>
<p>If a mock method shouldn't be called at all, explicitly say so:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(_))</div>
<div class="line">      .Times(0);</div>
</div><!-- fragment --><p>If some calls to the method are allowed, but the rest are not, just list all the expected calls:</p>
<div class="fragment"><div class="line">using ::testing::AnyNumber;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(5));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(Gt(10)))</div>
<div class="line">      .Times(AnyNumber());</div>
</div><!-- fragment --><p>A call to <code>foo.Bar()</code> that doesn't match any of the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statements will be an error.</p>
<h2><a class="anchor" id="uninteresting-vs-unexpected"></a>
Understanding Uninteresting vs Unexpected Calls</h2>
<p><em>Uninteresting</em> calls and <em>unexpected</em> calls are different concepts in gMock. <em>Very</em> different.</p>
<p>A call <code>x.Y(...)</code> is <b>uninteresting</b> if there's <em>not even a single</em> <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL(x, Y(...))</a></code> set. In other words, the test isn't interested in the <code>x.Y()</code> method at all, as evident in that the test doesn't care to say anything about it.</p>
<p>A call <code>x.Y(...)</code> is <b>unexpected</b> if there are <em>some</em> <code>EXPECT_CALL(x, Y(...))</code>s set, but none of them matches the call. Put another way, the test is interested in the <code>x.Y()</code> method (therefore it explicitly sets some <code>EXPECT_CALL</code> to verify how it's called); however, the verification fails as the test doesn't expect this particular call to happen.</p>
<p><b>An unexpected call is always an error,</b> as the code under test doesn't behave the way the test expects it to behave.</p>
<p><b>By default, an uninteresting call is not an error,</b> as it violates no constraint specified by the test. (gMock's philosophy is that saying nothing means there is no constraint.) However, it leads to a warning, as it <em>might</em> indicate a problem (e.g. the test author might have forgotten to specify a constraint).</p>
<p>In gMock, <code>NiceMock</code> and <code>StrictMock</code> can be used to make a mock class "nice" or "strict". How does this affect uninteresting calls and unexpected calls?</p>
<p>A <b>nice mock</b> suppresses uninteresting call <em>warnings</em>. It is less chatty than the default mock, but otherwise is the same. If a test fails with a default mock, it will also fail using a nice mock instead. And vice versa. Don't expect making a mock nice to change the test's result.</p>
<p>A <b>strict mock</b> turns uninteresting call warnings into errors. So making a mock strict may change the test's result.</p>
<p>Let's look at an example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(...) {</div>
<div class="line">  NiceMock&lt;MockDomainRegistry&gt; mock_registry;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_registry, GetDomainOwner(<span class="stringliteral">&quot;google.com&quot;</span>))</div>
<div class="line">          .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="stringliteral">&quot;Larry Page&quot;</span>));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Use mock_registry in code under test.</span></div>
<div class="line">  ... &amp;mock_registry ...</div>
<div class="line">}</div>
</div><!-- fragment --><p>The sole <code>EXPECT_CALL</code> here says that all calls to <code>GetDomainOwner()</code> must have <code>"google.com"</code> as the argument. If <code>GetDomainOwner("yahoo.com")</code> is called, it will be an unexpected call, and thus an error. <em>Having a nice mock doesn't change the severity of an unexpected call.</em></p>
<p>So how do we tell gMock that <code>GetDomainOwner()</code> can be called with some other arguments as well? The standard technique is to add a "catch all" <code>EXPECT_CALL</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_registry, GetDomainOwner(_))</div>
<div class="line">      .Times(AnyNumber());  <span class="comment">// catches all other calls to this method.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_registry, GetDomainOwner(<span class="stringliteral">&quot;google.com&quot;</span>))</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="stringliteral">&quot;Larry Page&quot;</span>));</div>
</div><!-- fragment --><p>Remember that <code>_</code> is the wildcard matcher that matches anything. With this, if <code>GetDomainOwner("google.com")</code> is called, it will do what the second <code>EXPECT_CALL</code> says; if it is called with a different argument, it will do what the first <code>EXPECT_CALL</code> says.</p>
<p>Note that the order of the two <code>EXPECT_CALL</code>s is important, as a newer <code>EXPECT_CALL</code> takes precedence over an older one.</p>
<p>For more on uninteresting calls, nice mocks, and strict mocks, read <a href="#NiceStrictNaggy">"The Nice, the Strict, and the Naggy"</a>.</p>
<h2><a class="anchor" id="ParameterlessExpectations"></a>
Ignoring Uninteresting Arguments</h2>
<p>If your test doesn't care about the parameters (it only cares about the number or order of calls), you can often simply omit the parameter list:</p>
<div class="fragment"><div class="line"><span class="comment">// Expect foo.Bar( ... ) twice with any arguments.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar).Times(2);</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Delegate to the given method whenever the factory is invoked.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(foo_factory, MakeFoo)</div>
<div class="line">    .WillByDefault(&amp;BuildFooForTest);</div>
</div><!-- fragment --><p>This functionality is only available when a method is not overloaded; to prevent unexpected behavior it is a compilation error to try to set an expectation on a method where the specific overload is ambiguous. You can work around this by supplying a <a href="#SimplerInterfaces">simpler mock interface</a> than the mocked class provides.</p>
<p>This pattern is also useful when the arguments are interesting, but match logic is substantially complex. You can leave the argument list unspecified and use SaveArg actions to <a href="#SaveArgVerify">save the values for later verification</a>. If you do that, you can easily differentiate calling the method the wrong number of times from calling it with the wrong arguments.</p>
<h2><a class="anchor" id="OrderedCalls"></a>
Expecting Ordered Calls</h2>
<p>Although an <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statement defined later takes precedence when gMock tries to match a function call with an expectation, by default calls don't have to happen in the order <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statements are written. For example, if the arguments match the matchers in the second <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>, but not those in the first and third, then the second expectation will be used.</p>
<p>If you would rather have all calls occur in the order of the expectations, put the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statements in a block where you define a variable of type <code>InSequence</code>:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::InSequence;</div>
<div class="line"> </div>
<div class="line">  {</div>
<div class="line">    InSequence s;</div>
<div class="line"> </div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(5));</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(bar, DoThat(_))</div>
<div class="line">        .Times(2);</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(6));</div>
<div class="line">  }</div>
</div><!-- fragment --><p>In this example, we expect a call to <code>foo.DoThis(5)</code>, followed by two calls to <code>bar.DoThat()</code> where the argument can be anything, which are in turn followed by a call to <code>foo.DoThis(6)</code>. If a call occurred out-of-order, gMock will report an error.</p>
<h2><a class="anchor" id="PartialOrder"></a>
Expecting Partially Ordered Calls</h2>
<p>Sometimes requiring everything to occur in a predetermined order can lead to brittle tests. For example, we may care about <code>A</code> occurring before both <code>B</code> and <code>C</code>, but aren't interested in the relative order of <code>B</code> and <code>C</code>. In this case, the test should reflect our real intent, instead of being overly constraining.</p>
<p>gMock allows you to impose an arbitrary DAG (directed acyclic graph) on the calls. One way to express the DAG is to use the <a href="gmock_cheat_sheet.md#AfterClause">After</a> clause of <code>EXPECT_CALL</code>.</p>
<p>Another way is via the <code>InSequence()</code> clause (not the same as the <code>InSequence</code> class), which we borrowed from jMock 2. It's less flexible than <code>After()</code>, but more convenient when you have long chains of sequential calls, as it doesn't require you to come up with different names for the expectations in the chains. Here's how it works:</p>
<p>If we view <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> statements as nodes in a graph, and add an edge from node A to node B wherever A must occur before B, we can get a DAG. We use the term "sequence" to mean a directed path in this DAG. Now, if we decompose the DAG into sequences, we just need to know which sequences each <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> belongs to in order to be able to reconstruct the original DAG.</p>
<p>So, to specify the partial order on the expectations we need to do two things: first to define some <code>Sequence</code> objects, and then for each <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code> say which <code>Sequence</code> objects it is part of.</p>
<p>Expectations in the same sequence must occur in the order they are written. For example,</p>
<div class="fragment"><div class="line">using ::testing::Sequence;</div>
<div class="line">...</div>
<div class="line">  Sequence s1, s2;</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, A())</div>
<div class="line">      .InSequence(s1, s2);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(bar, B())</div>
<div class="line">      .InSequence(s1);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(bar, C())</div>
<div class="line">      .InSequence(s2);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, D())</div>
<div class="line">      .InSequence(s2);</div>
</div><!-- fragment --><p>specifies the following DAG (where <code>s1</code> is <code>A -&gt; B</code>, and <code>s2</code> is <code>A -&gt; C -&gt; D</code>):</p>
<div class="fragment"><div class="line">     +---&gt; B</div>
<div class="line">     |</div>
<div class="line">A ---|</div>
<div class="line">     |</div>
<div class="line">      +---&gt; C ---&gt; D</div>
</div><!-- fragment --><p>This means that A must occur before B and C, and C must occur before D. There's no restriction about the order other than these.</p>
<h2><a class="anchor" id="autotoc_md161"></a>
Controlling When an Expectation Retires</h2>
<p>When a mock method is called, gMock only considers expectations that are still active. An expectation is active when created, and becomes inactive (aka <em>retires</em>) when a call that has to occur later has occurred. For example, in</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::Sequence;</div>
<div class="line">...</div>
<div class="line">  Sequence s1, s2;</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, <span class="stringliteral">&quot;File too large.&quot;</span>))      <span class="comment">// #1</span></div>
<div class="line">      .Times(AnyNumber())</div>
<div class="line">      .InSequence(s1, s2);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, <span class="stringliteral">&quot;Data set is empty.&quot;</span>))   <span class="comment">// #2</span></div>
<div class="line">      .InSequence(s1);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, <span class="stringliteral">&quot;User not found.&quot;</span>))      <span class="comment">// #3</span></div>
<div class="line">      .InSequence(s2);</div>
</div><!-- fragment --><p>as soon as either #2 or #3 is matched, #1 will retire. If a warning <code>"File too
large."</code> is logged after this, it will be an error.</p>
<p>Note that an expectation doesn't retire automatically when it's saturated. For example,</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, _));                     <span class="comment">// #1</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, <span class="stringliteral">&quot;File too large.&quot;</span>));     <span class="comment">// #2</span></div>
</div><!-- fragment --><p>says that there will be exactly one warning with the message <code>"File too
large."</code>. If the second warning contains this message too, #2 will match again and result in an upper-bound-violated error.</p>
<p>If this is not what you want, you can ask an expectation to retire as soon as it becomes saturated:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, _));                     <span class="comment">// #1</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(log, <a class="code" href="namespacetesting_1_1internal.html#a8a57ce0412334a3f487bbaa8321febbe">Log</a>(WARNING, _, <span class="stringliteral">&quot;File too large.&quot;</span>))      <span class="comment">// #2</span></div>
<div class="line">      .RetiresOnSaturation();</div>
</div><!-- fragment --><p>Here #2 can be used only once, so if you have two warnings with the message <code>"File too large."</code>, the first will match #2 and the second will match #1 - there will be no error.</p>
<h1><a class="anchor" id="autotoc_md162"></a>
Using Actions</h1>
<h2><a class="anchor" id="autotoc_md163"></a>
Returning References from Mock Methods</h2>
<p>If a mock function's return type is a reference, you need to use <code><a class="el" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef()</a></code> instead of <code><a class="el" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return()</a></code> to return a result:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">using ::testing::ReturnRef</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(Bar&amp;, GetBar, (), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  Bar bar;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, GetBar())</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef</a>(bar));</div>
<div class="line">...</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md164"></a>
Returning Live Values from Mock Methods</h2>
<p>The <code>Return(x)</code> action saves a copy of <code>x</code> when the action is created, and always returns the same value whenever it's executed. Sometimes you may want to instead return the <em>live</em> value of <code>x</code> (i.e. its value at the time when the action is <em>executed</em>.). Use either <code><a class="el" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef()</a></code> or <code><a class="el" href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">ReturnPointee()</a></code> for this purpose.</p>
<p>If the mock function's return type is a reference, you can do it using <code>ReturnRef(x)</code>, as shown in the previous recipe ("Returning References from Mock
Methods"). However, gMock doesn't let you use <code><a class="el" href="namespacetesting.html#ac17089d5ca6377944d3792fbdc5c5d9b">ReturnRef()</a></code> in a mock function whose return type is not a reference, as doing that usually indicates a user error. So, what shall you do?</p>
<p>Though you may be tempted, DO NOT use <code>std::ref()</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> <a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">testing::Return</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, GetValue, (), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line">...</div>
<div class="line">  <span class="keywordtype">int</span> x = 0;</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, GetValue())</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(std::ref(x)));  <span class="comment">// Wrong!</span></div>
<div class="line">  x = 42;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(42, foo.GetValue());</div>
</div><!-- fragment --><p>Unfortunately, it doesn't work here. The above code will fail with error:</p>
<div class="fragment"><div class="line">Value of: foo.GetValue()</div>
<div class="line">  Actual: 0</div>
<div class="line">Expected: 42</div>
</div><!-- fragment --><p>The reason is that <code>Return(*value*)</code> converts <code>value</code> to the actual return type of the mock function at the time when the action is <em>created</em>, not when it is <em>executed</em>. (This behavior was chosen for the action to be safe when <code>value</code> is a proxy object that references some temporary objects.) As a result, <code>std::ref(x)</code> is converted to an <code>int</code> value (instead of a <code>const int&amp;</code>) when the expectation is set, and <code>Return(std::ref(x))</code> will always return 0.</p>
<p><code>ReturnPointee(pointer)</code> was provided to solve this problem specifically. It returns the value pointed to by <code>pointer</code> at the time the action is <em>executed</em>:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> <a class="code" href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">testing::ReturnPointee</a>;</div>
<div class="line">...</div>
<div class="line">  <span class="keywordtype">int</span> x = 0;</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, GetValue())</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">ReturnPointee</a>(&amp;x));  <span class="comment">// Note the &amp; here.</span></div>
<div class="line">  x = 42;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(42, foo.GetValue());  <span class="comment">// This will succeed now.</span></div>
<div class="ttc" id="anamespacetesting_html_a3277ba2ea50e4a7b5db1f36a9ea8b070"><div class="ttname"><a href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">testing::ReturnPointee</a></div><div class="ttdeci">internal::ReturnPointeeAction&lt; Ptr &gt; ReturnPointee(Ptr pointer)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1452</div></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md165"></a>
Combining Actions</h2>
<p>Want to do more than one thing when a function is called? That's fine. <code><a class="el" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll()</a></code> allow you to do sequence of actions every time. Only the return value of the last action in the sequence will be used.</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">using ::testing::DoAll</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, Bar, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(_))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll</a>(action_1,</div>
<div class="line">                      action_2,</div>
<div class="line">                      ...</div>
<div class="line">                      action_n));</div>
<div class="ttc" id="anamespacetesting_html_a3824c79dc6e9e05c337a675e82da2045"><div class="ttname"><a href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">testing::DoAll</a></div><div class="ttdeci">internal::DoAllAction&lt; typename std::decay&lt; Action &gt;::type... &gt; DoAll(Action &amp;&amp;... action)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1204</div></div>
</div><!-- fragment --><h2><a class="anchor" id="SaveArgVerify"></a>
Verifying Complex Arguments</h2>
<p>If you want to verify that a method is called with a particular argument but the match criteria is complex, it can be difficult to distinguish between cardinality failures (calling the method the wrong number of times) and argument match failures. Similarly, if you are matching multiple parameters, it may not be easy to distinguishing which argument failed to match. For example:</p>
<div class="fragment"><div class="line"><span class="comment">// Not ideal: this could fail because of a problem with arg1 or arg2, or maybe</span></div>
<div class="line"><span class="comment">// just the method wasn&#39;t called.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... )));</div>
</div><!-- fragment --><p>You can instead save the arguments and test them individually:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, SendValues)</div>
<div class="line">    .WillOnce(<a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll</a>(SaveArg&lt;1&gt;(&amp;actual_array), SaveArg&lt;2&gt;(&amp;actual_proto)));</div>
<div class="line">... run the test</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(actual_array, ElementsAre(1, 4, 4, 7));</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(actual_proto, EqualsProto( ... ));</div>
</div><!-- fragment --><h2><a class="anchor" id="MockingSideEffects"></a>
Mocking Side Effects</h2>
<p>Sometimes a method exhibits its effect not via returning a value but via side effects. For example, it may change some global state or modify an output argument. To mock side effects, in general you can define your own action by implementing <code><a class="el" href="classtesting_1_1_action_interface.html">testing::ActionInterface</a></code>.</p>
<p>If all you need to do is to change an output argument, the built-in <code><a class="el" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">SetArgPointee()</a></code> action is convenient:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">using ::testing::SetArgPointee</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockMutator : <span class="keyword">public</span> Mutator {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Mutate, (<span class="keywordtype">bool</span> mutate, <span class="keywordtype">int</span>* value), (<span class="keyword">override</span>));</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  MockMutator mutator;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mutator, Mutate(<span class="keyword">true</span>, _))</div>
<div class="line">      .WillOnce(SetArgPointee&lt;1&gt;(5));</div>
<div class="ttc" id="anamespacetesting_html_a6e0d2e2c84a1fc7477fcb84be09d5560"><div class="ttname"><a href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">testing::SetArgPointee</a></div><div class="ttdeci">internal::SetArgumentPointeeAction&lt; N, T &gt; SetArgPointee(T value)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1310</div></div>
</div><!-- fragment --><p>In this example, when <code>mutator.Mutate()</code> is called, we will assign 5 to the <code>int</code> variable pointed to by argument #1 (0-based).</p>
<p><code><a class="el" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">SetArgPointee()</a></code> conveniently makes an internal copy of the value you pass to it, removing the need to keep the value in scope and alive. The implication however is that the value must have a copy constructor and assignment operator.</p>
<p>If the mock method also needs to return a value as well, you can chain <code><a class="el" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">SetArgPointee()</a></code> with <code><a class="el" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return()</a></code> using <code><a class="el" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll()</a></code>, remembering to put the <code><a class="el" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return()</a></code> statement last:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">using ::testing::SetArgPointee</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockMutator : <span class="keyword">public</span> Mutator {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, MutateInt, (<span class="keywordtype">int</span>* value), (<span class="keyword">override</span>));</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  MockMutator mutator;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mutator, MutateInt(_))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll</a>(SetArgPointee&lt;0&gt;(5),</div>
<div class="line">                      <a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">true</span>)));</div>
</div><!-- fragment --><p>Note, however, that if you use the <code>ReturnOKWith()</code> method, it will override the values provided by <code><a class="el" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">SetArgPointee()</a></code> in the response parameters of your function call.</p>
<p>If the output argument is an array, use the <code>SetArrayArgument&lt;N&gt;(first, last)</code> action instead. It copies the elements in source range <code>[first, last)</code> to the array pointed to by the <code>N</code>-th (0-based) argument:</p>
<div class="fragment"><div class="line">using ::testing::NotNull;</div>
<div class="line"><a class="code" href="namespacetesting.html#a2a7c63dd6a2f46c354608d99ba35e761">using ::testing::SetArrayArgument</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockArrayMutator : <span class="keyword">public</span> ArrayMutator {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Mutate, (<span class="keywordtype">int</span>* values, <span class="keywordtype">int</span> num_values), (<span class="keyword">override</span>));</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  MockArrayMutator mutator;</div>
<div class="line">  <span class="keywordtype">int</span> values[5] = {1, 2, 3, 4, 5};</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mutator, Mutate(NotNull(), 5))</div>
<div class="line">      .WillOnce(SetArrayArgument&lt;0&gt;(values, values + 5));</div>
<div class="ttc" id="anamespacetesting_html_a2a7c63dd6a2f46c354608d99ba35e761"><div class="ttname"><a href="namespacetesting.html#a2a7c63dd6a2f46c354608d99ba35e761">testing::SetArrayArgument</a></div><div class="ttdeci">internal::SetArrayArgumentAction&lt; k, I1, I2 &gt; SetArrayArgument(I1 first, I2 last)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1438</div></div>
</div><!-- fragment --><p>This also works when the argument is an output iterator:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#a2a7c63dd6a2f46c354608d99ba35e761">using ::testing::SetArrayArgument</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockRolodex : <span class="keyword">public</span> Rolodex {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, GetNames, (std::back_insert_iterator&lt;vector&lt;string&gt;&gt;),</div>
<div class="line">              (<span class="keyword">override</span>));</div>
<div class="line">  ...</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  MockRolodex rolodex;</div>
<div class="line">  vector&lt;string&gt; names;</div>
<div class="line">  names.push_back(<span class="stringliteral">&quot;George&quot;</span>);</div>
<div class="line">  names.push_back(<span class="stringliteral">&quot;John&quot;</span>);</div>
<div class="line">  names.push_back(<span class="stringliteral">&quot;Thomas&quot;</span>);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(rolodex, GetNames(_))</div>
<div class="line">      .WillOnce(SetArrayArgument&lt;0&gt;(names.begin(), names.end()));</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md166"></a>
Changing a Mock Object's Behavior Based on the State</h2>
<p>If you expect a call to change the behavior of a mock object, you can use <code>::testing::InSequence</code> to specify different behaviors before and after the call:</p>
<div class="fragment"><div class="line">using ::testing::InSequence;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  {</div>
<div class="line">     InSequence seq;</div>
<div class="line">     <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(my_mock, IsDirty())</div>
<div class="line">         .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">true</span>));</div>
<div class="line">     <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(my_mock, Flush());</div>
<div class="line">     <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(my_mock, IsDirty())</div>
<div class="line">         .WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">false</span>));</div>
<div class="line">  }</div>
<div class="line">  my_mock.FlushIfDirty();</div>
</div><!-- fragment --><p>This makes <code>my_mock.IsDirty()</code> return <code>true</code> before <code>my_mock.Flush()</code> is called and return <code>false</code> afterwards.</p>
<p>If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#a0fee053995e93f1b1efc97a33ae1a5b2">using ::testing::SaveArg</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(<a class="code" href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">ReturnPointee</a>, p) { <span class="keywordflow">return</span> *p; }</div>
<div class="line">...</div>
<div class="line">  <span class="keywordtype">int</span> previous_value = 0;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(my_mock, GetPrevValue)</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#a3277ba2ea50e4a7b5db1f36a9ea8b070">ReturnPointee</a>(&amp;previous_value));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(my_mock, UpdateValue)</div>
<div class="line">      .WillRepeatedly(SaveArg&lt;0&gt;(&amp;previous_value));</div>
<div class="line">  my_mock.DoSomethingToUpdateValue();</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h_html_af5f47e069acb517db9f743f029471aa7"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a></div><div class="ttdeci">#define ACTION_P(name,...)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1651</div></div>
<div class="ttc" id="anamespacetesting_html_a0fee053995e93f1b1efc97a33ae1a5b2"><div class="ttname"><a href="namespacetesting.html#a0fee053995e93f1b1efc97a33ae1a5b2">testing::SaveArg</a></div><div class="ttdeci">internal::SaveArgAction&lt; k, Ptr &gt; SaveArg(Ptr pointer)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1413</div></div>
</div><!-- fragment --><p>Here <code>my_mock.GetPrevValue()</code> will always return the argument of the last <code>UpdateValue()</code> call.</p>
<h2><a class="anchor" id="DefaultValue"></a>
Setting the Default Value for a Return Type</h2>
<p>If a mock method's return type is a built-in C++ type or pointer, by default it will return 0 when invoked. Also, in C++ 11 and above, a mock method whose return type has a default constructor will return a default-constructed value by default. You only need to specify an action if this default value doesn't work for you.</p>
<p>Sometimes, you may want to change this default value, or you may want to specify a default value for types gMock doesn't know about. You can do this using the <code><a class="el" href="classtesting_1_1_default_value.html">testing::DefaultValue</a></code> class template:</p>
<div class="fragment"><div class="line">using ::testing::DefaultValue;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(Bar, CalculateBar, (), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  Bar default_bar;</div>
<div class="line">  <span class="comment">// Sets the default return value for type Bar.</span></div>
<div class="line">  DefaultValue&lt;Bar&gt;::Set(default_bar);</div>
<div class="line"> </div>
<div class="line">  MockFoo foo;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// We don&#39;t need to specify an action here, as the default</span></div>
<div class="line">  <span class="comment">// return value works for us.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, CalculateBar());</div>
<div class="line"> </div>
<div class="line">  foo.CalculateBar();  <span class="comment">// This should return default_bar.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Unsets the default return value.</span></div>
<div class="line">  DefaultValue&lt;Bar&gt;::Clear();</div>
</div><!-- fragment --><p>Please note that changing the default value for a type can make your tests hard to understand. We recommend you to use this feature judiciously. For example, you may want to make sure the <code>Set()</code> and <code>Clear()</code> calls are right next to the code that uses your mock.</p>
<h2><a class="anchor" id="autotoc_md167"></a>
Setting the Default Actions for a Mock Method</h2>
<p>You've learned how to change the default value of a given type. However, this may be too coarse for your purpose: perhaps you have two mock methods with the same return type and you want them to have different behaviors. The <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> macro allows you to customize your mock's behavior at the method level:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::AnyNumber;</div>
<div class="line">using ::testing::Gt;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(foo, Sign(_))</div>
<div class="line">      .WillByDefault(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(-1));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(foo, Sign(0))</div>
<div class="line">      .WillByDefault(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(0));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL</a>(foo, Sign(Gt(0)))</div>
<div class="line">      .WillByDefault(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(1));</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Sign(_))</div>
<div class="line">      .Times(AnyNumber());</div>
<div class="line"> </div>
<div class="line">  foo.Sign(5);   <span class="comment">// This should return 1.</span></div>
<div class="line">  foo.Sign(-9);  <span class="comment">// This should return -1.</span></div>
<div class="line">  foo.Sign(0);   <span class="comment">// This should return 0.</span></div>
</div><!-- fragment --><p>As you may have guessed, when there are more than one <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> statements, the newer ones in the order take precedence over the older ones. In other words, the <b>last</b> one that matches the function arguments will be used. This matching order allows you to set up the common behavior in a mock object's constructor or the test fixture's set-up phase and specialize the mock's behavior later.</p>
<p>Note that both <code>ON_CALL</code> and <code>EXPECT_CALL</code> have the same "later statements take
precedence" rule, but they don't interact. That is, <code>EXPECT_CALL</code>s have their own precedence order distinct from the <code>ON_CALL</code> precedence order.</p>
<h2><a class="anchor" id="FunctionsAsActions"></a>
Using Functions/Methods/Functors/Lambdas as Actions</h2>
<p>If the built-in actions don't suit you, you can use an existing callable (function, <code>std::function</code>, method, functor, lambda) as an action.</p>
<div class="fragment"><div class="line">using ::testing::_; <a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, Sum, (<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, ComplexJob, (<span class="keywordtype">int</span> x), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> CalculateSum(<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y) { <span class="keywordflow">return</span> x + y; }</div>
<div class="line"><span class="keywordtype">int</span> Sum3(<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y, <span class="keywordtype">int</span> z) { <span class="keywordflow">return</span> x + y + z; }</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>Helper {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">bool</span> ComplexJob(<span class="keywordtype">int</span> x);</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  Helper helper;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Sum(_, _))</div>
<div class="line">      .WillOnce(&amp;CalculateSum)</div>
<div class="line">      .WillRepeatedly(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(NewPermanentCallback(Sum3, 1)));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, ComplexJob(_))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(&amp;helper, &amp;Helper::ComplexJob))</div>
<div class="line">      .WillOnce([] { <span class="keywordflow">return</span> <span class="keyword">true</span>; })</div>
<div class="line">      .WillRepeatedly([](<span class="keywordtype">int</span> x) { <span class="keywordflow">return</span> x &gt; 0; });</div>
<div class="line"> </div>
<div class="line">  foo.Sum(5, 6);         <span class="comment">// Invokes CalculateSum(5, 6).</span></div>
<div class="line">  foo.Sum(2, 3);         <span class="comment">// Invokes Sum3(1, 2, 3).</span></div>
<div class="line">  foo.ComplexJob(10);    <span class="comment">// Invokes helper.ComplexJob(10).</span></div>
<div class="line">  foo.ComplexJob(-1);    <span class="comment">// Invokes the inline lambda.</span></div>
<div class="ttc" id="anamespacetesting_html_af5cacf4475557b5a3e37af3836564235"><div class="ttname"><a href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">testing::Invoke</a></div><div class="ttdeci">std::decay&lt; FunctionImpl &gt;::type Invoke(FunctionImpl &amp;&amp;function_impl)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1345</div></div>
</div><!-- fragment --><p>The only requirement is that the type of the function, etc must be <em>compatible</em> with the signature of the mock function, meaning that the latter's arguments (if it takes any) can be implicitly converted to the corresponding arguments of the former, and the former's return type can be implicitly converted to that of the latter. So, you can invoke something whose type is <em>not</em> exactly the same as the mock function, as long as it's safe to do so - nice, huh?</p>
<p>Note that:</p>
<ul>
<li>The action takes ownership of the callback and will delete it when the action itself is destructed.</li>
<li><p class="startli">If the type of a callback is derived from a base callback type <code>C</code>, you need to implicitly cast it to <code>C</code> to resolve the overloading, e.g.</p>
<p class="startli">```cpp using <a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">testing::Invoke</a>; ... ResultCallback&lt;bool&gt;* is_ok = ...; ... Invoke(is_ok) ...; // This works.</p>
<p class="startli">BlockingClosure* done = new BlockingClosure; ... Invoke(implicit_cast&lt;Closure*&gt;(done)) ...; // The cast is necessary. ```</p>
</li>
</ul>
<h2><a class="anchor" id="autotoc_md168"></a>
Using Functions with Extra Info as Actions</h2>
<p>The function or functor you call using <code><a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke()</a></code> must have the same number of arguments as the mock function you use it for. Sometimes you may have a function that takes more arguments, and you are willing to pass in the extra arguments yourself to fill the gap. You can do this in gMock using callbacks with pre-bound arguments. Here's an example:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">char</span>, DoThis, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">char</span> SignOfSum(<span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y) {</div>
<div class="line">  <span class="keyword">const</span> <span class="keywordtype">int</span> sum = x + y;</div>
<div class="line">  <span class="keywordflow">return</span> (sum &gt; 0) ? <span class="charliteral">&#39;+&#39;</span> : (sum &lt; 0) ? <span class="charliteral">&#39;-&#39;</span> : <span class="charliteral">&#39;0&#39;</span>;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a0ee66d464d1a06c20c1929cae09d8758">TEST_F</a>(FooTest, Test) {</div>
<div class="line">  MockFoo foo;</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(2))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(NewPermanentCallback(SignOfSum, 5)));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(<span class="charliteral">&#39;+&#39;</span>, foo.DoThis(2));  <span class="comment">// Invokes SignOfSum(5, 2).</span></div>
<div class="line">}</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_a0ee66d464d1a06c20c1929cae09d8758"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a0ee66d464d1a06c20c1929cae09d8758">TEST_F</a></div><div class="ttdeci">#define TEST_F(test_fixture, test_name)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:2365</div></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md169"></a>
Invoking a Function/Method/Functor/Lambda/Callback Without Arguments</h2>
<p><code><a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke()</a></code> passes the mock function's arguments to the function, etc being invoked such that the callee has the full context of the call to work with. If the invoked function is not interested in some or all of the arguments, it can simply ignore them.</p>
<p>Yet, a common pattern is that a test author wants to invoke a function without the arguments of the mock function. She could do that using a wrapper function that throws away the arguments before invoking an underlining nullary function. Needless to say, this can be tedious and obscures the intent of the test.</p>
<p>There are two solutions to this problem. First, you can pass any callable of zero args as an action. Alternatively, use <code><a class="el" href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">InvokeWithoutArgs()</a></code>, which is like <code><a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke()</a></code> except that it doesn't pass the mock function's arguments to the callee. Here's an example of each:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">using ::testing::InvokeWithoutArgs</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, ComplexJob, (<span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">bool</span> Job1() { ... }</div>
<div class="line"><span class="keywordtype">bool</span> Job2(<span class="keywordtype">int</span> n, <span class="keywordtype">char</span> c) { ... }</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, ComplexJob(_))</div>
<div class="line">      .WillOnce([] { Job1(); });</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">InvokeWithoutArgs</a>(NewPermanentCallback(Job2, 5, <span class="charliteral">&#39;a&#39;</span>)));</div>
<div class="line"> </div>
<div class="line">  foo.ComplexJob(10);  <span class="comment">// Invokes Job1().</span></div>
<div class="line">  foo.ComplexJob(20);  <span class="comment">// Invokes Job2(5, &#39;a&#39;).</span></div>
<div class="ttc" id="anamespacetesting_html_aabc08d610483908c8346f2e3318ad449"><div class="ttname"><a href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">testing::InvokeWithoutArgs</a></div><div class="ttdeci">internal::InvokeWithoutArgsAction&lt; typename std::decay&lt; FunctionImpl &gt;::type &gt; InvokeWithoutArgs(FunctionImpl function_impl)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1360</div></div>
</div><!-- fragment --><p>Note that:</p>
<ul>
<li>The action takes ownership of the callback and will delete it when the action itself is destructed.</li>
<li><p class="startli">If the type of a callback is derived from a base callback type <code>C</code>, you need to implicitly cast it to <code>C</code> to resolve the overloading, e.g.</p>
<p class="startli">```cpp using <a class="el" href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">testing::InvokeWithoutArgs</a>; ... ResultCallback&lt;bool&gt;* is_ok = ...; ... InvokeWithoutArgs(is_ok) ...; // This works.</p>
<p class="startli">BlockingClosure* done = ...; ... InvokeWithoutArgs(implicit_cast&lt;Closure*&gt;(done)) ...; // The cast is necessary. ```</p>
</li>
</ul>
<h2><a class="anchor" id="autotoc_md170"></a>
Invoking an Argument of the Mock Function</h2>
<p>Sometimes a mock function will receive a function pointer, a functor (in other words, a "callable") as an argument, e.g.</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, DoThis, (<span class="keywordtype">int</span> n, (ResultCallback1&lt;bool, int&gt;* callback)),</div>
<div class="line">              (<span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><p>and you may want to invoke this callable argument:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(_, _))</div>
<div class="line">      .WillOnce(...);</div>
<div class="line">      <span class="comment">// Will execute callback-&gt;Run(5), where callback is the</span></div>
<div class="line">      <span class="comment">// second argument DoThis() receives.</span></div>
</div><!-- fragment --><p>{: .callout .note} NOTE: The section below is legacy documentation from before C++ had lambdas:</p>
<p>Arghh, you need to refer to a mock function argument but C++ has no lambda (yet), so you have to define your own action. :-( Or do you really?</p>
<p>Well, gMock has an action to solve <em>exactly</em> this problem:</p>
<div class="fragment"><div class="line">InvokeArgument&lt;N&gt;(arg_1, arg_2, ..., arg_m)</div>
</div><!-- fragment --><p>will invoke the <code>N</code>-th (0-based) argument the mock function receives, with <code>arg_1</code>, <code>arg_2</code>, ..., and <code>arg_m</code>. No matter if the argument is a function pointer, a functor, or a callback. gMock handles them all.</p>
<p>With that, you could write:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting_1_1internal.html#a4c6f0469015303fe29a4f08ba036e6d6">using ::testing::InvokeArgument</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis(_, _))</div>
<div class="line">      .WillOnce(InvokeArgument&lt;1&gt;(5));</div>
<div class="line">      <span class="comment">// Will execute callback-&gt;Run(5), where callback is the</span></div>
<div class="line">      <span class="comment">// second argument DoThis() receives.</span></div>
<div class="ttc" id="anamespacetesting_1_1internal_html_a4c6f0469015303fe29a4f08ba036e6d6"><div class="ttname"><a href="namespacetesting_1_1internal.html#a4c6f0469015303fe29a4f08ba036e6d6">testing::internal::InvokeArgument</a></div><div class="ttdeci">auto InvokeArgument(F f, Args... args) -&gt; decltype(f(args...))</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-more-actions.h:509</div></div>
</div><!-- fragment --><p>What if the callable takes an argument by reference? No problem - just wrap it inside <code>std::ref()</code>:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">MOCK_METHOD(<span class="keywordtype">bool</span>, Bar,</div>
<div class="line">            ((ResultCallback2&lt;bool, int, const Helper&amp;&gt;* callback)),</div>
<div class="line">            (<span class="keyword">override</span>));</div>
<div class="line">...</div>
<div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting_1_1internal.html#a4c6f0469015303fe29a4f08ba036e6d6">using ::testing::InvokeArgument</a>;</div>
<div class="line">...</div>
<div class="line">MockFoo foo;</div>
<div class="line">Helper helper;</div>
<div class="line">...</div>
<div class="line">EXPECT_CALL(foo, Bar(_))</div>
<div class="line">    .WillOnce(InvokeArgument&lt;0&gt;(5, std::ref(helper)));</div>
<div class="line">    <span class="comment">// std::ref(helper) guarantees that a reference to helper, not a copy of</span></div>
<div class="line">    <span class="comment">// it, will be passed to the callback.</span></div>
</div><!-- fragment --><p>What if the callable takes an argument by reference and we do <b>not</b> wrap the argument in <code>std::ref()</code>? Then <code><a class="el" href="namespacetesting_1_1internal.html#a4c6f0469015303fe29a4f08ba036e6d6">InvokeArgument()</a></code> will <em>make a copy</em> of the argument, and pass a <em>reference to the copy</em>, instead of a reference to the original value, to the callable. This is especially handy when the argument is a temporary value:</p>
<div class="fragment"><div class="line">...</div>
<div class="line">MOCK_METHOD(<span class="keywordtype">bool</span>, DoThat, (<span class="keywordtype">bool</span> (*f)(<span class="keyword">const</span> <span class="keywordtype">double</span>&amp; x, <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; s)),</div>
<div class="line">            (<span class="keyword">override</span>));</div>
<div class="line">...</div>
<div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting_1_1internal.html#a4c6f0469015303fe29a4f08ba036e6d6">using ::testing::InvokeArgument</a>;</div>
<div class="line">...</div>
<div class="line">MockFoo foo;</div>
<div class="line">...</div>
<div class="line">EXPECT_CALL(foo, DoThat(_))</div>
<div class="line">    .WillOnce(InvokeArgument&lt;0&gt;(5.0, <span class="keywordtype">string</span>(<span class="stringliteral">&quot;Hi&quot;</span>)));</div>
<div class="line">    <span class="comment">// Will execute (*f)(5.0, string(&quot;Hi&quot;)), where f is the function pointer</span></div>
<div class="line">    <span class="comment">// DoThat() receives.  Note that the values 5.0 and string(&quot;Hi&quot;) are</span></div>
<div class="line">    <span class="comment">// temporary and dead once the EXPECT_CALL() statement finishes.  Yet</span></div>
<div class="line">    <span class="comment">// it&#39;s fine to perform this action later, since a copy of the values</span></div>
<div class="line">    <span class="comment">// are kept inside the InvokeArgument action.</span></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md171"></a>
Ignoring an Action's Result</h2>
<p>Sometimes you have an action that returns <em>something</em>, but you need an action that returns <code>void</code> (perhaps you want to use it in a mock function that returns <code>void</code>, or perhaps it needs to be used in <code><a class="el" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll()</a></code> and it's not the last in the list). <code><a class="el" href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">IgnoreResult()</a></code> lets you do that. For example:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">using ::testing::DoAll</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">using ::testing::IgnoreResult</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">int</span> Process(<span class="keyword">const</span> MyData&amp; data);</div>
<div class="line"><span class="keywordtype">string</span> DoSomething();</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Abc, (<span class="keyword">const</span> MyData&amp; data), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, Xyz, (), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">  ...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Abc(_))</div>
<div class="line">      <span class="comment">// .WillOnce(Invoke(Process));</span></div>
<div class="line">      <span class="comment">// The above line won&#39;t compile as Process() returns int but Abc() needs</span></div>
<div class="line">      <span class="comment">// to return void.</span></div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">IgnoreResult</a>(Process));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Xyz())</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll</a>(<a class="code" href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">IgnoreResult</a>(DoSomething),</div>
<div class="line">                      <span class="comment">// Ignores the string DoSomething() returns.</span></div>
<div class="line">                      <a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">true</span>)));</div>
<div class="ttc" id="anamespacetesting_html_a257c9395b54e9267a0348a6310128889"><div class="ttname"><a href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">testing::IgnoreResult</a></div><div class="ttdeci">internal::IgnoreResultAction&lt; A &gt; IgnoreResult(const A &amp;an_action)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1376</div></div>
</div><!-- fragment --><p>Note that you <b>cannot</b> use <code><a class="el" href="namespacetesting.html#a257c9395b54e9267a0348a6310128889">IgnoreResult()</a></code> on an action that already returns <code>void</code>. Doing so will lead to ugly compiler errors.</p>
<h2><a class="anchor" id="SelectingArgs"></a>
Selecting an Action's Arguments</h2>
<p>Say you have a mock function <code>Foo()</code> that takes seven arguments, and you have a custom action that you want to invoke when <code>Foo()</code> is called. Trouble is, the custom action only wants three arguments:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, Foo,</div>
<div class="line">              (<span class="keywordtype">bool</span> visible, <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; name, <span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y,</div>
<div class="line">               (<span class="keyword">const</span> <a class="code" href="group__map__pattern.html#gaf326a6fa32cef31ddb3379cfc042edfe">map</a>&lt;pair&lt;int, int&gt;&gt;), <span class="keywordtype">double</span>&amp; weight, <span class="keywordtype">double</span> min_weight,</div>
<div class="line">               <span class="keywordtype">double</span> max_wight));</div>
<div class="line">...</div>
<div class="line">bool IsVisibleInQuadrant1(<span class="keywordtype">bool</span> visible, <span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y) {</div>
<div class="line">  <span class="keywordflow">return</span> visible &amp;&amp; x &gt;= 0 &amp;&amp; y &gt;= 0;</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo)</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(IsVisibleInQuadrant1));  <span class="comment">// Uh, won&#39;t compile. :-(</span></div>
<div class="ttc" id="agroup__map__pattern_html_gaf326a6fa32cef31ddb3379cfc042edfe"><div class="ttname"><a href="group__map__pattern.html#gaf326a6fa32cef31ddb3379cfc042edfe">grppi::map</a></div><div class="ttdeci">void map(const Execution &amp;ex, std::tuple&lt; InputIterators... &gt; firsts, InputIt last, OutputIt first_out, Transformer transform_op)</div><div class="ttdoc">Invoke Map pattern on a data sequence.</div><div class="ttdef"><b>Definition:</b> map.h:51</div></div>
</div><!-- fragment --><p>To please the compiler God, you need to define an "adaptor" that has the same signature as <code>Foo()</code> and calls the custom action with the right arguments:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line">...</div>
<div class="line">bool MyIsVisibleInQuadrant1(<span class="keywordtype">bool</span> visible, <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; name, <span class="keywordtype">int</span> x, <span class="keywordtype">int</span> y,</div>
<div class="line">                            <span class="keyword">const</span> <a class="code" href="group__map__pattern.html#gaf326a6fa32cef31ddb3379cfc042edfe">map</a>&lt;pair&lt;int, int&gt;, <span class="keywordtype">double</span>&gt;&amp; weight,</div>
<div class="line">                            <span class="keywordtype">double</span> min_weight, <span class="keywordtype">double</span> max_wight) {</div>
<div class="line">  <span class="keywordflow">return</span> IsVisibleInQuadrant1(visible, x, y);</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo)</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(MyIsVisibleInQuadrant1));  <span class="comment">// Now it works.</span></div>
</div><!-- fragment --><p>But isn't this awkward?</p>
<p>gMock provides a generic <em>action adaptor</em>, so you can spend your time minding more important business than writing your own adaptors. Here's the syntax:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#a4b8dc8233e7b92226ffe51e0d0040604">WithArgs</a>&lt;N1, N2, ..., Nk&gt;(action)</div>
<div class="ttc" id="anamespacetesting_html_a4b8dc8233e7b92226ffe51e0d0040604"><div class="ttname"><a href="namespacetesting.html#a4b8dc8233e7b92226ffe51e0d0040604">testing::WithArgs</a></div><div class="ttdeci">internal::WithArgsAction&lt; typename std::decay&lt; InnerAction &gt;::type, k, ks... &gt; WithArgs(InnerAction &amp;&amp;action)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1226</div></div>
</div><!-- fragment --><p>creates an action that passes the arguments of the mock function at the given indices (0-based) to the inner <code>action</code> and performs it. Using <code>WithArgs</code>, our original example can be written as:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#a4b8dc8233e7b92226ffe51e0d0040604">using ::testing::WithArgs</a>;</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo)</div>
<div class="line">      .WillOnce(WithArgs&lt;0, 2, 3&gt;(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(IsVisibleInQuadrant1)));  <span class="comment">// No need to define your own adaptor.</span></div>
</div><!-- fragment --><p>For better readability, gMock also gives you:</p>
<ul>
<li><code>WithoutArgs(action)</code> when the inner <code>action</code> takes <em>no</em> argument, and</li>
<li><code>WithArg&lt;N&gt;(action)</code> (no <code>s</code> after <code>Arg</code>) when the inner <code>action</code> takes <em>one</em> argument.</li>
</ul>
<p>As you may have realized, <code>InvokeWithoutArgs(...)</code> is just syntactic sugar for <code>WithoutArgs(Invoke(...))</code>.</p>
<p>Here are more tips:</p>
<ul>
<li>The inner action used in <code>WithArgs</code> and friends does not have to be <code><a class="el" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke()</a></code> &ndash; it can be anything.</li>
<li>You can repeat an argument in the argument list if necessary, e.g. <code>WithArgs&lt;2, 3, 3, 5&gt;(...)</code>.</li>
<li>You can change the order of the arguments, e.g. <code>WithArgs&lt;3, 2, 1&gt;(...)</code>.</li>
<li>The types of the selected arguments do <em>not</em> have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an <code>int</code> and <code>my_action</code> takes a <code>double</code>, <code>WithArg&lt;4&gt;(my_action)</code> will work.</li>
</ul>
<h2><a class="anchor" id="autotoc_md172"></a>
Ignoring Arguments in Action Functions</h2>
<p>The <a href="#SelectingArgs">selecting-an-action's-arguments</a> recipe showed us one way to make a mock function and an action with incompatible argument lists fit together. The downside is that wrapping the action in <code>WithArgs&lt;...&gt;()</code> can get tedious for people writing the tests.</p>
<p>If you are defining a function (or method, functor, lambda, callback) to be used with <code>Invoke*()</code>, and you are not interested in some of its arguments, an alternative to <code>WithArgs</code> is to declare the uninteresting arguments as <code>Unused</code>. This makes the definition less cluttered and less fragile in case the types of the uninteresting arguments change. It could also increase the chance the action function can be reused. For example, given</p>
<div class="fragment"><div class="line"><span class="keyword">public</span>:</div>
<div class="line"> <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">double</span>, Foo, <span class="keywordtype">double</span>(<span class="keyword">const</span> <span class="keywordtype">string</span>&amp; label, <span class="keywordtype">double</span> x, <span class="keywordtype">double</span> y),</div>
<div class="line">             (<span class="keyword">override</span>));</div>
<div class="line"> <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">double</span>, Bar, (<span class="keywordtype">int</span> index, <span class="keywordtype">double</span> x, <span class="keywordtype">double</span> y), (<span class="keyword">override</span>));</div>
</div><!-- fragment --><p>instead of</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">double</span> DistanceToOriginWithLabel(<span class="keyword">const</span> <span class="keywordtype">string</span>&amp; label, <span class="keywordtype">double</span> x, <span class="keywordtype">double</span> y) {</div>
<div class="line">  <span class="keywordflow">return</span> sqrt(x*x + y*y);</div>
<div class="line">}</div>
<div class="line"><span class="keywordtype">double</span> DistanceToOriginWithIndex(<span class="keywordtype">int</span> index, <span class="keywordtype">double</span> x, <span class="keywordtype">double</span> y) {</div>
<div class="line">  <span class="keywordflow">return</span> sqrt(x*x + y*y);</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(<span class="stringliteral">&quot;abc&quot;</span>, _, _))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(DistanceToOriginWithLabel));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Bar(5, _, _))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(DistanceToOriginWithIndex));</div>
</div><!-- fragment --><p>you could write</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"><a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">using ::testing::Invoke</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#a603e329ec0263ebfcf16f712810bd511">using ::testing::Unused</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keywordtype">double</span> DistanceToOrigin(<a class="code" href="namespacetesting.html#a603e329ec0263ebfcf16f712810bd511">Unused</a>, <span class="keywordtype">double</span> x, <span class="keywordtype">double</span> y) {</div>
<div class="line">  <span class="keywordflow">return</span> sqrt(x*x + y*y);</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(<span class="stringliteral">&quot;abc&quot;</span>, _, _))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(DistanceToOrigin));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Bar(5, _, _))</div>
<div class="line">      .WillOnce(<a class="code" href="namespacetesting.html#af5cacf4475557b5a3e37af3836564235">Invoke</a>(DistanceToOrigin));</div>
<div class="ttc" id="anamespacetesting_html_a603e329ec0263ebfcf16f712810bd511"><div class="ttname"><a href="namespacetesting.html#a603e329ec0263ebfcf16f712810bd511">testing::Unused</a></div><div class="ttdeci">internal::IgnoredValue Unused</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1198</div></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md173"></a>
Sharing Actions</h2>
<p>Just like matchers, a gMock action object consists of a pointer to a ref-counted implementation object. Therefore copying actions is also allowed and very efficient. When the last action that references the implementation object dies, the implementation object will be deleted.</p>
<p>If you have some complex action that you want to use again and again, you may not have to build it from scratch everytime. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example:</p>
<div class="fragment"><div class="line">using ::testing::Action;</div>
<div class="line"><a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">using ::testing::DoAll</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">using ::testing::SetArgPointee</a>;</div>
<div class="line">...</div>
<div class="line">  Action&lt;bool(<span class="keywordtype">int</span>*)&gt; set_flag = <a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">DoAll</a>(SetArgPointee&lt;0&gt;(5),</div>
<div class="line">                                      <a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">true</span>));</div>
<div class="line">  ... use set_flag in .WillOnce() and .WillRepeatedly() ...</div>
</div><!-- fragment --><p>However, if the action has its own state, you may be surprised if you share the action object. Suppose you have an action factory <code>IncrementCounter(init)</code> which creates an action that increments and returns a counter whose initial value is <code>init</code>, using two actions created from the same expression and using a shared action will exhibit different behaviors. Example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis())</div>
<div class="line">    .WillRepeatedly(IncrementCounter(0));</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat())</div>
<div class="line">    .WillRepeatedly(IncrementCounter(0));</div>
<div class="line">foo.DoThis();  <span class="comment">// Returns 1.</span></div>
<div class="line">foo.DoThis();  <span class="comment">// Returns 2.</span></div>
<div class="line">foo.DoThat();  <span class="comment">// Returns 1 - Blah() uses a different</span></div>
<div class="line">               <span class="comment">// counter than Bar()&#39;s.</span></div>
</div><!-- fragment --><p>versus</p>
<div class="fragment"><div class="line">using ::testing::Action;</div>
<div class="line">...</div>
<div class="line">  Action&lt;int()&gt; increment = IncrementCounter(0);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis())</div>
<div class="line">      .WillRepeatedly(increment);</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat())</div>
<div class="line">      .WillRepeatedly(increment);</div>
<div class="line">  foo.DoThis();  <span class="comment">// Returns 1.</span></div>
<div class="line">  foo.DoThis();  <span class="comment">// Returns 2.</span></div>
<div class="line">  foo.DoThat();  <span class="comment">// Returns 3 - the counter is shared.</span></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md174"></a>
Testing Asynchronous Behavior</h2>
<p>One oft-encountered problem with gMock is that it can be hard to test asynchronous behavior. Suppose you had a <code>EventQueue</code> class that you wanted to test, and you created a separate <code>EventDispatcher</code> interface so that you could easily mock it out. However, the implementation of the class fired all the events on a background thread, which made test timings difficult. You could just insert <code>sleep()</code> statements and hope for the best, but that makes your test behavior nondeterministic. A better way is to use gMock actions and <code>Notification</code> objects to force your asynchronous test to behave synchronously.</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#a3824c79dc6e9e05c337a675e82da2045">using ::testing::DoAll</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#aabc08d610483908c8346f2e3318ad449">using ::testing::InvokeWithoutArgs</a>;</div>
<div class="line"><a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">using ::testing::Return</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockEventDispatcher : <span class="keyword">public</span> EventDispatcher {</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, DispatchEvent, (int32), (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(Notify, notification) {</div>
<div class="line">  notification-&gt;Notify();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(EventQueueTest, EnqueueEventTest) {</div>
<div class="line">  MockEventDispatcher mock_event_dispatcher;</div>
<div class="line">  EventQueue event_queue(&amp;mock_event_dispatcher);</div>
<div class="line"> </div>
<div class="line">  <span class="keyword">const</span> int32 kEventId = 321;</div>
<div class="line">  absl::Notification done;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_event_dispatcher, DispatchEvent(kEventId))</div>
<div class="line">      .WillOnce(Notify(&amp;done));</div>
<div class="line"> </div>
<div class="line">  event_queue.EnqueueEvent(kEventId);</div>
<div class="line">  done.WaitForNotification();</div>
<div class="line">}</div>
</div><!-- fragment --><p>In the example above, we set our normal gMock expectations, but then add an additional action to notify the <code>Notification</code> object. Now we can just call <code>Notification::WaitForNotification()</code> in the main thread to wait for the asynchronous call to finish. After that, our test suite is complete and we can safely exit.</p>
<p>{: .callout .note} Note: this example has a downside: namely, if the expectation is not satisfied, our test will run forever. It will eventually time-out and fail, but it will take longer and be slightly harder to debug. To alleviate this problem, you can use <code>WaitForNotificationWithTimeout(ms)</code> instead of <code>WaitForNotification()</code>.</p>
<h1><a class="anchor" id="autotoc_md175"></a>
Misc Recipes on Using gMock</h1>
<h2><a class="anchor" id="autotoc_md176"></a>
Mocking Methods That Use Move-Only Types</h2>
<p>C++11 introduced <em>move-only types</em>. A move-only-typed value can be moved from one object to another, but cannot be copied. <code>std::unique_ptr&lt;T&gt;</code> is probably the most commonly used move-only type.</p>
<p>Mocking a method that takes and/or returns move-only types presents some challenges, but nothing insurmountable. This recipe shows you how you can do it. Note that the support for move-only method arguments was only introduced to gMock in April 2017; in older code, you may find more complex <a href="#LegacyMoveOnly">workarounds</a> for lack of this feature.</p>
<p>Let’s say we are working on a fictional project that lets one post and share snippets called “buzzes”. Your code uses these types:</p>
<div class="fragment"><div class="line"><span class="keyword">enum class</span> AccessLevel { kInternal, kPublic };</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>Buzz {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">explicit</span> Buzz(AccessLevel access) { ... }</div>
<div class="line">  ...</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>Buzzer {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~Buzzer() {}</div>
<div class="line">  <span class="keyword">virtual</span> std::unique_ptr&lt;Buzz&gt; MakeBuzz(StringPiece text) = 0;</div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> ShareBuzz(std::unique_ptr&lt;Buzz&gt; buzz, int64_t timestamp) = 0;</div>
<div class="line">  ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>A <code>Buzz</code> object represents a snippet being posted. A class that implements the <code>Buzzer</code> interface is capable of creating and sharing <code>Buzz</code>es. Methods in <code>Buzzer</code> may return a <code>unique_ptr&lt;Buzz&gt;</code> or take a <code>unique_ptr&lt;Buzz&gt;</code>. Now we need to mock <code>Buzzer</code> in our tests.</p>
<p>To mock a method that accepts or returns move-only types, you just use the familiar <code>MOCK_METHOD</code> syntax as usual:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockBuzzer : <span class="keyword">public</span> Buzzer {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(std::unique_ptr&lt;Buzz&gt;, MakeBuzz, (StringPiece text), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, ShareBuzz, (std::unique_ptr&lt;Buzz&gt; buzz, int64_t timestamp),</div>
<div class="line">              (<span class="keyword">override</span>));</div>
<div class="line">};</div>
</div><!-- fragment --><p>Now that we have the mock class defined, we can use it in tests. In the following code examples, we assume that we have defined a <code>MockBuzzer</code> object named <code>mock_buzzer_</code>:</p>
<div class="fragment"><div class="line">MockBuzzer mock_buzzer_;</div>
</div><!-- fragment --><p>First let’s see how we can set expectations on the <code>MakeBuzz()</code> method, which returns a <code>unique_ptr&lt;Buzz&gt;</code>.</p>
<p>As usual, if you set an expectation without an action (i.e. the <code>.WillOnce()</code> or <code>.WillRepeatedly()</code> clause), when that expectation fires, the default action for that method will be taken. Since <code>unique_ptr&lt;&gt;</code> has a default constructor that returns a null <code>unique_ptr</code>, that’s what you’ll get if you don’t specify an action:</p>
<div class="fragment"><div class="line"><span class="comment">// Use the default action.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, MakeBuzz(<span class="stringliteral">&quot;hello&quot;</span>));</div>
<div class="line"> </div>
<div class="line"><span class="comment">// Triggers the previous EXPECT_CALL.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a4159019abda84f5366acdb7604ff220a">EXPECT_EQ</a>(<span class="keyword">nullptr</span>, mock_buzzer_.MakeBuzz(<span class="stringliteral">&quot;hello&quot;</span>));</div>
</div><!-- fragment --><p>If you are not happy with the default action, you can tweak it as usual; see <a href="#OnCall">Setting Default Actions</a>.</p>
<p>If you just need to return a pre-defined move-only value, you can use the <code>Return(ByMove(...))</code> action:</p>
<div class="fragment"><div class="line"><span class="comment">// When this fires, the unique_ptr&lt;&gt; specified by ByMove(...) will</span></div>
<div class="line"><span class="comment">// be returned.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, MakeBuzz(<span class="stringliteral">&quot;world&quot;</span>))</div>
<div class="line">    .WillOnce(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<a class="code" href="namespacetesting.html#a38293837852ef2c406b063741018d108">ByMove</a>(MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal))));</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a6ae7443947f25abc58bfcfcfc56b0d75">EXPECT_NE</a>(<span class="keyword">nullptr</span>, mock_buzzer_.MakeBuzz(<span class="stringliteral">&quot;world&quot;</span>));</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_a6ae7443947f25abc58bfcfcfc56b0d75"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a6ae7443947f25abc58bfcfcfc56b0d75">EXPECT_NE</a></div><div class="ttdeci">#define EXPECT_NE(val1, val2)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:2026</div></div>
<div class="ttc" id="anamespacetesting_html_a38293837852ef2c406b063741018d108"><div class="ttname"><a href="namespacetesting.html#a38293837852ef2c406b063741018d108">testing::ByMove</a></div><div class="ttdeci">internal::ByMoveWrapper&lt; R &gt; ByMove(R x)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1281</div></div>
</div><!-- fragment --><p>Note that <code><a class="el" href="namespacetesting.html#a38293837852ef2c406b063741018d108">ByMove()</a></code> is essential here - if you drop it, the code won’t compile.</p>
<p>Quiz time! What do you think will happen if a <code>Return(ByMove(...))</code> action is performed more than once (e.g. you write <code>... .WillRepeatedly(Return(ByMove(...)));</code>)? Come think of it, after the first time the action runs, the source value will be consumed (since it’s a move-only value), so the next time around, there’s no value to move from &ndash; you’ll get a run-time error that <code>Return(ByMove(...))</code> can only be run once.</p>
<p>If you need your mock method to do more than just moving a pre-defined value, remember that you can always use a lambda or a callable object, which can do pretty much anything you want:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, MakeBuzz(<span class="stringliteral">&quot;x&quot;</span>))</div>
<div class="line">    .WillRepeatedly([](StringPiece text) {</div>
<div class="line">      <span class="keywordflow">return</span> MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal);</div>
<div class="line">    });</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a6ae7443947f25abc58bfcfcfc56b0d75">EXPECT_NE</a>(<span class="keyword">nullptr</span>, mock_buzzer_.MakeBuzz(<span class="stringliteral">&quot;x&quot;</span>));</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#a6ae7443947f25abc58bfcfcfc56b0d75">EXPECT_NE</a>(<span class="keyword">nullptr</span>, mock_buzzer_.MakeBuzz(<span class="stringliteral">&quot;x&quot;</span>));</div>
</div><!-- fragment --><p>Every time this <code>EXPECT_CALL</code> fires, a new <code>unique_ptr&lt;Buzz&gt;</code> will be created and returned. You cannot do this with <code>Return(ByMove(...))</code>.</p>
<p>That covers returning move-only values; but how do we work with methods accepting move-only arguments? The answer is that they work normally, although some actions will not compile when any of method's arguments are move-only. You can always use <code>Return</code>, or a <a href="#FunctionsAsActions">lambda or functor</a>:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#a603e329ec0263ebfcf16f712810bd511">using ::testing::Unused</a>;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(<span class="keyword">true</span>));</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ac33e7cdfb5d44a7a0f0ab552eb5c3c6a">EXPECT_TRUE</a>(mock_buzzer_.ShareBuzz(MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal)),</div>
<div class="line">            0);</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, ShareBuzz(_, _)).WillOnce(</div>
<div class="line">    [](std::unique_ptr&lt;Buzz&gt; buzz, <a class="code" href="namespacetesting.html#a603e329ec0263ebfcf16f712810bd511">Unused</a>) { <span class="keywordflow">return</span> buzz != <span class="keyword">nullptr</span>; });</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#aeb6c7ae89f440c90c1a1815951c836da">EXPECT_FALSE</a>(mock_buzzer_.ShareBuzz(<span class="keyword">nullptr</span>, 0));</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_ac33e7cdfb5d44a7a0f0ab552eb5c3c6a"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ac33e7cdfb5d44a7a0f0ab552eb5c3c6a">EXPECT_TRUE</a></div><div class="ttdeci">#define EXPECT_TRUE(condition)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:1965</div></div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h_html_aeb6c7ae89f440c90c1a1815951c836da"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#aeb6c7ae89f440c90c1a1815951c836da">EXPECT_FALSE</a></div><div class="ttdeci">#define EXPECT_FALSE(condition)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest.h:1968</div></div>
</div><!-- fragment --><p>Many built-in actions (<code>WithArgs</code>, <code>WithoutArgs</code>,<code>DeleteArg</code>, <code>SaveArg</code>, ...) could in principle support move-only arguments, but the support for this is not implemented yet. If this is blocking you, please file a bug.</p>
<p>A few actions (e.g. <code>DoAll</code>) copy their arguments internally, so they can never work with non-copyable objects; you'll have to use functors instead.</p>
<h3><a class="anchor" id="LegacyMoveOnly"></a>
Legacy workarounds for move-only types</h3>
<p>Support for move-only function arguments was only introduced to gMock in April of 2017. In older code, you may encounter the following workaround for the lack of this feature (it is no longer necessary - we're including it just for reference):</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockBuzzer : <span class="keyword">public</span> Buzzer {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, DoShareBuzz, (Buzz* buzz, Time timestamp));</div>
<div class="line">  <span class="keywordtype">bool</span> ShareBuzz(std::unique_ptr&lt;Buzz&gt; buzz, Time timestamp)<span class="keyword"> override </span>{</div>
<div class="line">    <span class="keywordflow">return</span> DoShareBuzz(buzz.get(), timestamp);</div>
<div class="line">  }</div>
<div class="line">};</div>
</div><!-- fragment --><p>The trick is to delegate the <code>ShareBuzz()</code> method to a mock method (let’s call it <code>DoShareBuzz()</code>) that does not take move-only parameters. Then, instead of setting expectations on <code>ShareBuzz()</code>, you set them on the <code>DoShareBuzz()</code> mock method:</p>
<div class="fragment"><div class="line">MockBuzzer mock_buzzer_;</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_buzzer_, DoShareBuzz(NotNull(), _));</div>
<div class="line"> </div>
<div class="line"><span class="comment">// When one calls ShareBuzz() on the MockBuzzer like this, the call is</span></div>
<div class="line"><span class="comment">// forwarded to DoShareBuzz(), which is mocked.  Therefore this statement</span></div>
<div class="line"><span class="comment">// will trigger the above EXPECT_CALL.</span></div>
<div class="line">mock_buzzer_.ShareBuzz(MakeUnique&lt;Buzz&gt;(AccessLevel::kInternal), 0);</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md177"></a>
Making the Compilation Faster</h2>
<p>Believe it or not, the <em>vast majority</em> of the time spent on compiling a mock class is in generating its constructor and destructor, as they perform non-trivial tasks (e.g. verification of the expectations). What's more, mock methods with different signatures have different types and thus their constructors/destructors need to be generated by the compiler separately. As a result, if you mock many different types of methods, compiling your mock class can get really slow.</p>
<p>If you are experiencing slow compilation, you can move the definition of your mock class' constructor and destructor out of the class body and into a <code>.cc</code> file. This way, even if you <code>#include</code> your mock class in N files, the compiler only needs to generate its constructor and destructor once, resulting in a much faster compilation.</p>
<p>Let's illustrate the idea using an example. Here's the definition of a mock class before applying this recipe:</p>
<div class="fragment"><div class="line"><span class="comment">// File mock_foo.h.</span></div>
<div class="line">...</div>
<div class="line">class MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// Since we don&#39;t declare the constructor or the destructor,</span></div>
<div class="line">  <span class="comment">// the compiler will generate them in every translation unit</span></div>
<div class="line">  <span class="comment">// where this mock class is used.</span></div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, DoThis, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, DoThat, (<span class="keyword">const</span> <span class="keywordtype">char</span>* str), (<span class="keyword">override</span>));</div>
<div class="line">  ... more mock methods ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>After the change, it would look like:</p>
<div class="fragment"><div class="line"><span class="comment">// File mock_foo.h.</span></div>
<div class="line">...</div>
<div class="line">class MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// The constructor and destructor are declared, but not defined, here.</span></div>
<div class="line">  MockFoo();</div>
<div class="line">  <span class="keyword">virtual</span> ~MockFoo();</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, DoThis, (), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">bool</span>, DoThat, (<span class="keyword">const</span> <span class="keywordtype">char</span>* str), (<span class="keyword">override</span>));</div>
<div class="line">  ... more mock methods ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>and</p>
<div class="fragment"><div class="line"><span class="comment">// File mock_foo.cc.</span></div>
<div class="line"><span class="preprocessor">#include &quot;path/to/mock_foo.h&quot;</span></div>
<div class="line"> </div>
<div class="line"><span class="comment">// The definitions may appear trivial, but the functions actually do a</span></div>
<div class="line"><span class="comment">// lot of things through the constructors/destructors of the member</span></div>
<div class="line"><span class="comment">// variables used to implement the mock methods.</span></div>
<div class="line">MockFoo::MockFoo() {}</div>
<div class="line">MockFoo::~MockFoo() {}</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md178"></a>
Forcing a Verification</h2>
<p>When it's being destroyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate googletest failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will be destroyed.</p>
<p>How could it be that your mock object won't eventually be destroyed? Well, it might be created on the heap and owned by the code you are testing. Suppose there's a bug in that code and it doesn't delete the mock object properly - you could end up with a passing test when there's actually a bug.</p>
<p>Using a heap checker is a good idea and can alleviate the concern, but its implementation is not 100% reliable. So, sometimes you do want to <em>force</em> gMock to verify a mock object before it is (hopefully) destructed. You can do this with <code>Mock::VerifyAndClearExpectations(&amp;mock_object)</code>:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(MyServerTest, ProcessesRequest) {</div>
<div class="line">  using ::testing::Mock;</div>
<div class="line"> </div>
<div class="line">  MockFoo* <span class="keyword">const</span> foo = <span class="keyword">new</span> MockFoo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(*foo, ...)...;</div>
<div class="line">  <span class="comment">// ... other expectations ...</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// server now owns foo.</span></div>
<div class="line">  MyServer server(foo);</div>
<div class="line">  server.ProcessRequest(...);</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// In case that server&#39;s destructor will forget to delete foo,</span></div>
<div class="line">  <span class="comment">// this will verify the expectations anyway.</span></div>
<div class="line">  Mock::VerifyAndClearExpectations(foo);</div>
<div class="line">}  <span class="comment">// server is destroyed when it goes out of scope here.</span></div>
</div><!-- fragment --><p>{: .callout .tip} <b>Tip:</b> The <code>Mock::VerifyAndClearExpectations()</code> function returns a <code>bool</code> to indicate whether the verification was successful (<code>true</code> for yes), so you can wrap that function call inside a <code><a class="el" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ae9244bfbda562e8b798789b001993fa5">ASSERT_TRUE()</a></code> if there is no point going further when the verification has failed.</p>
<h2><a class="anchor" id="UsingCheckPoints"></a>
Using Check Points</h2>
<p>Sometimes you may want to "reset" a mock object at various check points in your test: at each check point, you verify that all existing expectations on the mock object have been satisfied, and then you set some new expectations on it as if it's newly created. This allows you to work with a mock object in "phases" whose sizes are each manageable.</p>
<p>One such scenario is that in your test's <code>SetUp()</code> function, you may want to put the object you are testing into a certain state, with the help from a mock object. Once in the desired state, you want to clear all expectations on the mock, such that in the <code>TEST_F</code> body you can set fresh expectations on it.</p>
<p>As you may have figured out, the <code>Mock::VerifyAndClearExpectations()</code> function we saw in the previous recipe can help you here. Or, if you are using <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> to set default actions on the mock object and want to clear the default actions as well, use <code>Mock::VerifyAndClear(&amp;mock_object)</code> instead. This function does what <code>Mock::VerifyAndClearExpectations(&amp;mock_object)</code> does and returns the same <code>bool</code>, <b>plus</b> it clears the <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> statements on <code>mock_object</code> too.</p>
<p>Another trick you can use to achieve the same effect is to put the expectations in sequences and insert calls to a dummy "check-point" function at specific places. Then you can verify that the mock function calls do happen at the right time. For example, if you are exercising code:</p>
<div class="fragment"><div class="line">Foo(1);</div>
<div class="line">Foo(2);</div>
<div class="line">Foo(3);</div>
</div><!-- fragment --><p>and want to verify that <code>Foo(1)</code> and <code>Foo(3)</code> both invoke <code>mock.Bar("a")</code>, but <code>Foo(2)</code> doesn't invoke anything. You can write:</p>
<div class="fragment"><div class="line">using ::testing::MockFunction;</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(FooTest, InvokesBarCorrectly) {</div>
<div class="line">  MyMock mock;</div>
<div class="line">  <span class="comment">// Class MockFunction&lt;F&gt; has exactly one mock method.  It is named</span></div>
<div class="line">  <span class="comment">// Call() and has type F.</span></div>
<div class="line">  MockFunction&lt;void(<span class="keywordtype">string</span> check_point_name)&gt; check;</div>
<div class="line">  {</div>
<div class="line">    InSequence s;</div>
<div class="line"> </div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Bar(<span class="stringliteral">&quot;a&quot;</span>));</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(check, Call(<span class="stringliteral">&quot;1&quot;</span>));</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(check, Call(<span class="stringliteral">&quot;2&quot;</span>));</div>
<div class="line">    <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Bar(<span class="stringliteral">&quot;a&quot;</span>));</div>
<div class="line">  }</div>
<div class="line">  Foo(1);</div>
<div class="line">  check.Call(<span class="stringliteral">&quot;1&quot;</span>);</div>
<div class="line">  Foo(2);</div>
<div class="line">  check.Call(<span class="stringliteral">&quot;2&quot;</span>);</div>
<div class="line">  Foo(3);</div>
<div class="line">}</div>
</div><!-- fragment --><p>The expectation spec says that the first <code>Bar("a")</code> must happen before check point "1", the second <code>Bar("a")</code> must happen after check point "2", and nothing should happen between the two check points. The explicit check points make it easy to tell which <code>Bar("a")</code> is called by which call to <code>Foo()</code>.</p>
<h2><a class="anchor" id="autotoc_md179"></a>
Mocking Destructors</h2>
<p>Sometimes you want to make sure a mock object is destructed at the right time, e.g. after <code>bar-&gt;A()</code> is called but before <code>bar-&gt;B()</code> is called. We already know that you can specify constraints on the <a href="#OrderedCalls">order</a> of mock function calls, so all we need to do is to mock the destructor of the mock function.</p>
<p>This sounds simple, except for one problem: a destructor is a special function with special syntax and special semantics, and the <code>MOCK_METHOD</code> macro doesn't work for it:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, ~MockFoo, ());  <span class="comment">// Won&#39;t compile!</span></div>
</div><!-- fragment --><p>The good news is that you can use a simple pattern to achieve the same effect. First, add a mock function <code>Die()</code> to your mock class and call it in the destructor, like this:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line">  ...</div>
<div class="line">  <span class="comment">// Add the following two lines to the mock class.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, Die, ());</div>
<div class="line">  ~MockFoo()<span class="keyword"> override </span>{ Die(); }</div>
<div class="line">};</div>
</div><!-- fragment --><p>(If the name <code>Die()</code> clashes with an existing symbol, choose another name.) Now, we have translated the problem of testing when a <code>MockFoo</code> object dies to testing when its <code>Die()</code> method is called:</p>
<div class="fragment"><div class="line">MockFoo* foo = <span class="keyword">new</span> MockFoo;</div>
<div class="line">MockBar* bar = <span class="keyword">new</span> MockBar;</div>
<div class="line">...</div>
<div class="line">{</div>
<div class="line">  InSequence s;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Expects *foo to die after bar-&gt;A() and before bar-&gt;B().</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(*bar, A());</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(*foo, Die());</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(*bar, B());</div>
<div class="line">}</div>
</div><!-- fragment --><p>And that's that.</p>
<h2><a class="anchor" id="UsingThreads"></a>
Using gMock and Threads</h2>
<p>In a <b>unit</b> test, it's best if you could isolate and test a piece of code in a single-threaded context. That avoids race conditions and dead locks, and makes debugging your test much easier.</p>
<p>Yet most programs are multi-threaded, and sometimes to test something we need to pound on it from more than one thread. gMock works for this purpose too.</p>
<p>Remember the steps for using a mock:</p>
<ol type="1">
<li>Create a mock object <code>foo</code>.</li>
<li>Set its default actions and expectations using <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a5b12ae6cf84f0a544ca811b380c37334">ON_CALL()</a></code> and <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL()</a></code>.</li>
<li>The code under test calls methods of <code>foo</code>.</li>
<li>Optionally, verify and reset the mock.</li>
<li>Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.</li>
</ol>
<p>If you follow the following simple rules, your mocks and threads can live happily together:</p>
<ul>
<li>Execute your <em>test code</em> (as opposed to the code being tested) in <em>one</em> thread. This makes your test easy to follow.</li>
<li>Obviously, you can do step #1 without locking.</li>
<li>When doing step #2 and #5, make sure no other thread is accessing <code>foo</code>. Obvious too, huh?</li>
<li>#3 and #4 can be done either in one thread or in multiple threads - anyway you want. gMock takes care of the locking, so you don't have to do any - unless required by your test logic.</li>
</ul>
<p>If you violate the rules (for example, if you set expectations on a mock while another thread is calling its methods), you get undefined behavior. That's not fun, so don't do it.</p>
<p>gMock guarantees that the action for a mock function is done in the same thread that called the mock function. For example, in</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(1))</div>
<div class="line">    .WillOnce(action1);</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo(2))</div>
<div class="line">    .WillOnce(action2);</div>
</div><!-- fragment --><p>if <code>Foo(1)</code> is called in thread 1 and <code>Foo(2)</code> is called in thread 2, gMock will execute <code>action1</code> in thread 1 and <code>action2</code> in thread 2.</p>
<p>gMock does <em>not</em> impose a sequence on actions performed in different threads (doing so may create deadlocks as the actions may need to cooperate). This means that the execution of <code>action1</code> and <code>action2</code> in the above example <em>may</em> interleave. If this is a problem, you should add proper synchronization logic to <code>action1</code> and <code>action2</code> to make the test thread-safe.</p>
<p>Also, remember that <code>DefaultValue&lt;T&gt;</code> is a global resource that potentially affects <em>all</em> living mock objects in your program. Naturally, you won't want to mess with it from multiple threads or when there still are mocks in action.</p>
<h2><a class="anchor" id="autotoc_md180"></a>
Controlling How Much Information gMock Prints</h2>
<p>When gMock sees something that has the potential of being an error (e.g. a mock function with no expectation is called, a.k.a. an uninteresting call, which is allowed but perhaps you forgot to explicitly ban the call), it prints some warning messages, including the arguments of the function, the return value, and the stack trace. Hopefully this will remind you to take a look and see if there is indeed a problem.</p>
<p>Sometimes you are confident that your tests are correct and may not appreciate such friendly messages. Some other times, you are debugging your tests or learning about the behavior of the code you are testing, and wish you could observe every mock call that happens (including argument values, the return value, and the stack trace). Clearly, one size doesn't fit all.</p>
<p>You can control how much gMock tells you using the <code>--gmock_verbose=LEVEL</code> command-line flag, where <code>LEVEL</code> is a string with three possible values:</p>
<ul>
<li><code>info</code>: gMock will print all informational messages, warnings, and errors (most verbose). At this setting, gMock will also log any calls to the <code>ON_CALL/EXPECT_CALL</code> macros. It will include a stack trace in "uninteresting call" warnings.</li>
<li><code>warning</code>: gMock will print both warnings and errors (less verbose); it will omit the stack traces in "uninteresting call" warnings. This is the default.</li>
<li><code>error</code>: gMock will print errors only (least verbose).</li>
</ul>
<p>Alternatively, you can adjust the value of that flag from within your tests like so:</p>
<div class="fragment"><div class="line">::testing::FLAGS_gmock_verbose = <span class="stringliteral">&quot;error&quot;</span>;</div>
</div><!-- fragment --><p>If you find gMock printing too many stack frames with its informational or warning messages, remember that you can control their amount with the <code>--gtest_stack_trace_depth=max_depth</code> flag.</p>
<p>Now, judiciously use the right flag to enable gMock serve you better!</p>
<h2><a class="anchor" id="autotoc_md181"></a>
Gaining Super Vision into Mock Calls</h2>
<p>You have a test using gMock. It fails: gMock tells you some expectations aren't satisfied. However, you aren't sure why: Is there a typo somewhere in the matchers? Did you mess up the order of the <code>EXPECT_CALL</code>s? Or is the code under test doing something wrong? How can you find out the cause?</p>
<p>Won't it be nice if you have X-ray vision and can actually see the trace of all <code>EXPECT_CALL</code>s and mock method calls as they are made? For each call, would you like to see its actual argument values and which <code>EXPECT_CALL</code> gMock thinks it matches? If you still need some help to figure out who made these calls, how about being able to see the complete stack trace at each mock call?</p>
<p>You can unlock this power by running your test with the <code>--gmock_verbose=info</code> flag. For example, given the test program:</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &quot;gmock/gmock.h&quot;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">using</span> testing::_;</div>
<div class="line"><span class="keyword">using</span> testing::HasSubstr;</div>
<div class="line"><span class="keyword">using</span> <a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">testing::Return</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">void</span>, F, (<span class="keyword">const</span> <span class="keywordtype">string</span>&amp; x, <span class="keyword">const</span> <span class="keywordtype">string</span>&amp; y));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(Foo, Bar) {</div>
<div class="line">  MockFoo mock;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, F(_, _)).WillRepeatedly(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>());</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, F(<span class="stringliteral">&quot;a&quot;</span>, <span class="stringliteral">&quot;b&quot;</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, F(<span class="stringliteral">&quot;c&quot;</span>, HasSubstr(<span class="stringliteral">&quot;d&quot;</span>)));</div>
<div class="line"> </div>
<div class="line">  mock.F(<span class="stringliteral">&quot;a&quot;</span>, <span class="stringliteral">&quot;good&quot;</span>);</div>
<div class="line">  mock.F(<span class="stringliteral">&quot;a&quot;</span>, <span class="stringliteral">&quot;b&quot;</span>);</div>
<div class="line">}</div>
</div><!-- fragment --><p>if you run it with <code>--gmock_verbose=info</code>, you will see this output:</p>
<div class="fragment"><div class="line">[ RUN       ] Foo.Bar</div>
<div class="line"> </div>
<div class="line">foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked</div>
<div class="line">Stack trace: ...</div>
<div class="line"> </div>
<div class="line">foo_test.cc:15: EXPECT_CALL(mock, F(&quot;a&quot;, &quot;b&quot;)) invoked</div>
<div class="line">Stack trace: ...</div>
<div class="line"> </div>
<div class="line">foo_test.cc:16: EXPECT_CALL(mock, F(&quot;c&quot;, HasSubstr(&quot;d&quot;))) invoked</div>
<div class="line">Stack trace: ...</div>
<div class="line"> </div>
<div class="line">foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...</div>
<div class="line">    Function call: F(@0x7fff7c8dad40&quot;a&quot;,@0x7fff7c8dad10&quot;good&quot;)</div>
<div class="line">Stack trace: ...</div>
<div class="line"> </div>
<div class="line">foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F(&quot;a&quot;, &quot;b&quot;))...</div>
<div class="line">    Function call: F(@0x7fff7c8dada0&quot;a&quot;,@0x7fff7c8dad70&quot;b&quot;)</div>
<div class="line">Stack trace: ...</div>
<div class="line"> </div>
<div class="line">foo_test.cc:16: Failure</div>
<div class="line">Actual function call count doesn&#39;t match EXPECT_CALL(mock, F(&quot;c&quot;, HasSubstr(&quot;d&quot;)))...</div>
<div class="line">         Expected: to be called once</div>
<div class="line">           Actual: never called - unsatisfied and active</div>
<div class="line">[  FAILED  ] Foo.Bar</div>
</div><!-- fragment --><p>Suppose the bug is that the <code>"c"</code> in the third <code>EXPECT_CALL</code> is a typo and should actually be <code>"a"</code>. With the above message, you should see that the actual <code>F("a", "good")</code> call is matched by the first <code>EXPECT_CALL</code>, not the third as you thought. From that it should be obvious that the third <code>EXPECT_CALL</code> is written wrong. Case solved.</p>
<p>If you are interested in the mock call trace but not the stack traces, you can combine <code>--gmock_verbose=info</code> with <code>--gtest_stack_trace_depth=0</code> on the test command line.</p>
<h2><a class="anchor" id="autotoc_md182"></a>
Running Tests in Emacs</h2>
<p>If you build and run your tests in Emacs using the <code>M-x google-compile</code> command (as many googletest users do), the source file locations of gMock and googletest errors will be highlighted. Just press <code>&lt;Enter&gt;</code> on one of them and you'll be taken to the offending line. Or, you can just type <code>C-x</code>` to jump to the next error.</p>
<p>To make it even easier, you can add the following lines to your <code>~/.emacs</code> file:</p>
<div class="fragment"><div class="line">(global-set-key &quot;\M-m&quot;  &#39;google-compile)  ; m is for make</div>
<div class="line">(global-set-key [M-down] &#39;next-error)</div>
<div class="line">(global-set-key [M-up]  &#39;(lambda () (interactive) (next-error -1)))</div>
</div><!-- fragment --><p>Then you can type <code>M-m</code> to start a build (if you want to run the test as well, just make sure <code>foo_test.run</code> or <code>runtests</code> is in the build command you supply after typing <code>M-m</code>), or <code>M-up</code>/<code>M-down</code> to move back and forth between errors.</p>
<h1><a class="anchor" id="autotoc_md183"></a>
Extending gMock</h1>
<h2><a class="anchor" id="NewMatchers"></a>
Writing New Matchers Quickly</h2>
<p>{: .callout .warning} WARNING: gMock does not guarantee when or how many times a matcher will be invoked. Therefore, all matchers must be functionally pure. See <a href="#PureMatchers">this section</a> for more details.</p>
<p>The <code>MATCHER*</code> family of macros can be used to define custom matchers easily. The syntax:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#af4fe73ff8e2b0494f4970b575b65ddff">MATCHER</a>(name, description_string_expression) { statements; }</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h_html_af4fe73ff8e2b0494f4970b575b65ddff"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#af4fe73ff8e2b0494f4970b575b65ddff">MATCHER</a></div><div class="ttdeci">#define MATCHER(name, description)</div></div>
</div><!-- fragment --><p>will define a matcher with the given name that executes the statements, which must return a <code>bool</code> to indicate if the match succeeds. Inside the statements, you can refer to the value being matched by <code>arg</code>, and refer to its type by <code>arg_type</code>.</p>
<p>The <em>description string</em> is a <code>string</code>-typed expression that documents what the matcher does, and is used to generate the failure message when the match fails. It can (and should) reference the special <code>bool</code> variable <code>negation</code>, and should evaluate to the description of the matcher when <code>negation</code> is <code>false</code>, or that of the matcher's negation when <code>negation</code> is <code>true</code>.</p>
<p>For convenience, we allow the description string to be empty (<code>""</code>), in which case gMock will use the sequence of words in the matcher name as the description.</p>
<p>For example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#af4fe73ff8e2b0494f4970b575b65ddff">MATCHER</a>(IsDivisibleBy7, <span class="stringliteral">&quot;&quot;</span>) { <span class="keywordflow">return</span> (arg % 7) == 0; }</div>
</div><!-- fragment --><p>allows you to write</p>
<div class="fragment"><div class="line"><span class="comment">// Expects mock_foo.Bar(n) to be called where n is divisible by 7.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_foo, Bar(IsDivisibleBy7()));</div>
</div><!-- fragment --><p>or,</p>
<div class="fragment"><div class="line">using ::testing::Not;</div>
<div class="line">...</div>
<div class="line"><span class="comment">// Verifies that two values are divisible by 7.</span></div>
<div class="line">EXPECT_THAT(some_expression, IsDivisibleBy7());</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(some_other_expression, Not(IsDivisibleBy7()));</div>
</div><!-- fragment --><p>If the above assertions fail, they will print something like:</p>
<div class="fragment"><div class="line">Value of: some_expression</div>
<div class="line">Expected: is divisible by 7</div>
<div class="line">  Actual: 27</div>
<div class="line">...</div>
<div class="line">Value of: some_other_expression</div>
<div class="line">Expected: not (is divisible by 7)</div>
<div class="line">  Actual: 21</div>
</div><!-- fragment --><p>where the descriptions <code>"is divisible by 7"</code> and <code>"not (is divisible by 7)"</code> are automatically calculated from the matcher name <code>IsDivisibleBy7</code>.</p>
<p>As you may have noticed, the auto-generated descriptions (especially those for the negation) may not be so great. You can always override them with a <code>string</code> expression of your own:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#af4fe73ff8e2b0494f4970b575b65ddff">MATCHER</a>(IsDivisibleBy7,</div>
<div class="line">        absl::StrCat(negation ? <span class="stringliteral">&quot;isn&#39;t&quot;</span> : <span class="stringliteral">&quot;is&quot;</span>, <span class="stringliteral">&quot; divisible by 7&quot;</span>)) {</div>
<div class="line">  <span class="keywordflow">return</span> (arg % 7) == 0;</div>
<div class="line">}</div>
</div><!-- fragment --><p>Optionally, you can stream additional information to a hidden argument named <code>result_listener</code> to explain the match result. For example, a better definition of <code>IsDivisibleBy7</code> is:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#af4fe73ff8e2b0494f4970b575b65ddff">MATCHER</a>(IsDivisibleBy7, <span class="stringliteral">&quot;&quot;</span>) {</div>
<div class="line">  <span class="keywordflow">if</span> ((arg % 7) == 0)</div>
<div class="line">    <span class="keywordflow">return</span> <span class="keyword">true</span>;</div>
<div class="line"> </div>
<div class="line">  *result_listener &lt;&lt; <span class="stringliteral">&quot;the remainder is &quot;</span> &lt;&lt; (arg % 7);</div>
<div class="line">  <span class="keywordflow">return</span> <span class="keyword">false</span>;</div>
<div class="line">}</div>
</div><!-- fragment --><p>With this definition, the above assertion will give a better message:</p>
<div class="fragment"><div class="line">Value of: some_expression</div>
<div class="line">Expected: is divisible by 7</div>
<div class="line">  Actual: 27 (the remainder is 6)</div>
</div><!-- fragment --><p>You should let <code>MatchAndExplain()</code> print <em>any additional information</em> that can help a user understand the match result. Note that it should explain why the match succeeds in case of a success (unless it's obvious) - this is useful when the matcher is used inside <code>Not()</code>. There is no need to print the argument value itself, as gMock already prints it for you.</p>
<p>{: .callout .note} NOTE: The type of the value being matched (<code>arg_type</code>) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you). This allows the matcher to be polymorphic. For example, <code>IsDivisibleBy7()</code> can be used to match any type where the value of <code>(arg % 7) == 0</code> can be implicitly converted to a <code>bool</code>. In the <code>Bar(IsDivisibleBy7())</code> example above, if method <code>Bar()</code> takes an <code>int</code>, <code>arg_type</code> will be <code>int</code>; if it takes an <code>unsigned long</code>, <code>arg_type</code> will be <code>unsigned long</code>; and so on.</p>
<h2><a class="anchor" id="autotoc_md184"></a>
Writing New Parameterized Matchers Quickly</h2>
<p>Sometimes you'll want to define a matcher that has parameters. For that you can use the macro:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#acb7ae915efa2fd8d3f6ea7313198afb6">MATCHER_P</a>(name, param_name, description_string) { statements; }</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h_html_acb7ae915efa2fd8d3f6ea7313198afb6"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#acb7ae915efa2fd8d3f6ea7313198afb6">MATCHER_P</a></div><div class="ttdeci">#define MATCHER_P(name, p0, description)</div></div>
</div><!-- fragment --><p>where the description string can be either <code>""</code> or a <code>string</code> expression that references <code>negation</code> and <code>param_name</code>.</p>
<p>For example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#acb7ae915efa2fd8d3f6ea7313198afb6">MATCHER_P</a>(HasAbsoluteValue, value, <span class="stringliteral">&quot;&quot;</span>) { <span class="keywordflow">return</span> abs(arg) == value; }</div>
</div><!-- fragment --><p>will allow you to write:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT</a>(Blah(<span class="stringliteral">&quot;a&quot;</span>), HasAbsoluteValue(n));</div>
</div><!-- fragment --><p>which may lead to this message (assuming <code>n</code> is 10):</p>
<div class="fragment"><div class="line">Value of: Blah(&quot;a&quot;)</div>
<div class="line">Expected: has absolute value 10</div>
<div class="line">  Actual: -9</div>
</div><!-- fragment --><p>Note that both the matcher description and its parameter are printed, making the message human-friendly.</p>
<p>In the matcher definition body, you can write <code>foo_type</code> to reference the type of a parameter named <code>foo</code>. For example, in the body of <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#acb7ae915efa2fd8d3f6ea7313198afb6">MATCHER_P(HasAbsoluteValue, value)</a></code> above, you can write <code>value_type</code> to refer to the type of <code>value</code>.</p>
<p>gMock also provides <code>MATCHER_P2</code>, <code>MATCHER_P3</code>, ..., up to <code>MATCHER_P10</code> to support multi-parameter matchers:</p>
<div class="fragment"><div class="line">MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }</div>
</div><!-- fragment --><p>Please note that the custom description string is for a particular <em>instance</em> of the matcher, where the parameters have been bound to actual values. Therefore usually you'll want the parameter values to be part of the description. gMock lets you do that by referencing the matcher parameters in the description string expression.</p>
<p>For example,</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#aa5717bb1144edd1d262d310ba70c82ed">using ::testing::PrintToString</a>;</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a78efce3ad21c8f68223f5c2d09f2e79d">MATCHER_P2</a>(InClosedRange, low, hi,</div>
<div class="line">           absl::StrFormat(<span class="stringliteral">&quot;%s in range [%s, %s]&quot;</span>, negation ? <span class="stringliteral">&quot;isn&#39;t&quot;</span> : <span class="stringliteral">&quot;is&quot;</span>,</div>
<div class="line">                           <a class="code" href="namespacetesting.html#aa5717bb1144edd1d262d310ba70c82ed">PrintToString</a>(low), <a class="code" href="namespacetesting.html#aa5717bb1144edd1d262d310ba70c82ed">PrintToString</a>(hi))) {</div>
<div class="line">  <span class="keywordflow">return</span> low &lt;= arg &amp;&amp; arg &lt;= hi;</div>
<div class="line">}</div>
<div class="line">...</div>
<div class="line">EXPECT_THAT(3, InClosedRange(4, 6));</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h_html_a78efce3ad21c8f68223f5c2d09f2e79d"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a78efce3ad21c8f68223f5c2d09f2e79d">MATCHER_P2</a></div><div class="ttdeci">#define MATCHER_P2(name, p0, p1, description)</div></div>
<div class="ttc" id="anamespacetesting_html_aa5717bb1144edd1d262d310ba70c82ed"><div class="ttname"><a href="namespacetesting.html#aa5717bb1144edd1d262d310ba70c82ed">testing::PrintToString</a></div><div class="ttdeci">::std::string PrintToString(const T &amp;value)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest-printers.h:942</div></div>
</div><!-- fragment --><p>would generate a failure that contains the message:</p>
<div class="fragment"><div class="line">Expected: is in range [4, 6]</div>
</div><!-- fragment --><p>If you specify <code>""</code> as the description, the failure message will contain the sequence of words in the matcher name followed by the parameter values printed as a tuple. For example,</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a78efce3ad21c8f68223f5c2d09f2e79d">MATCHER_P2</a>(InClosedRange, low, hi, <span class="stringliteral">&quot;&quot;</span>) { ... }</div>
<div class="line">...</div>
<div class="line">EXPECT_THAT(3, InClosedRange(4, 6));</div>
</div><!-- fragment --><p>would generate a failure that contains the text:</p>
<div class="fragment"><div class="line">Expected: in closed range (4, 6)</div>
</div><!-- fragment --><p>For the purpose of typing, you can view</p>
<div class="fragment"><div class="line">MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }</div>
</div><!-- fragment --><p>as shorthand for</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> p1_type, ..., <span class="keyword">typename</span> pk_type&gt;</div>
<div class="line">FooMatcherPk&lt;p1_type, ..., pk_type&gt;</div>
<div class="line">Foo(p1_type p1, ..., pk_type pk) { ... }</div>
</div><!-- fragment --><p>When you write <code>Foo(v1, ..., vk)</code>, the compiler infers the types of the parameters <code>v1</code>, ..., and <code>vk</code> for you. If you are not happy with the result of the type inference, you can specify the types by explicitly instantiating the template, as in <code>Foo&lt;long, bool&gt;(5, false)</code>. As said earlier, you don't get to (or need to) specify <code>arg_type</code> as that's determined by the context in which the matcher is used.</p>
<p>You can assign the result of expression <code>Foo(p1, ..., pk)</code> to a variable of type <code>FooMatcherPk&lt;p1_type, ..., pk_type&gt;</code>. This can be useful when composing matchers. Matchers that don't have a parameter or have only one parameter have special types: you can assign <code>Foo()</code> to a <code>FooMatcher</code>-typed variable, and assign <code>Foo(p)</code> to a <code>FooMatcherP&lt;p_type&gt;</code>-typed variable.</p>
<p>While you can instantiate a matcher template with reference types, passing the parameters by pointer usually makes your code more readable. If, however, you still want to pass a parameter by reference, be aware that in the failure message generated by the matcher you will see the value of the referenced object but not its address.</p>
<p>You can overload matchers with different numbers of parameters:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#acb7ae915efa2fd8d3f6ea7313198afb6">MATCHER_P</a>(Blah, a, description_string_1) { ... }</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#a78efce3ad21c8f68223f5c2d09f2e79d">MATCHER_P2</a>(Blah, a, b, description_string_2) { ... }</div>
</div><!-- fragment --><p>While it's tempting to always use the <code>MATCHER*</code> macros when defining a new matcher, you should also consider implementing the matcher interface directly instead (see the recipes that follow), especially if you need to use the matcher a lot. While these approaches require more work, they give you more control on the types of the value being matched and the matcher parameters, which in general leads to better compiler error messages that pay off in the long run. They also allow overloading matchers based on parameter types (as opposed to just based on the number of parameters).</p>
<h2><a class="anchor" id="autotoc_md185"></a>
Writing New Monomorphic Matchers</h2>
<p>A matcher of argument type <code>T</code> implements the matcher interface for <code>T</code> and does two things: it tests whether a value of type <code>T</code> matches the matcher, and can describe what kind of values it matches. The latter ability is used for generating readable error messages when expectations are violated.</p>
<p>A matcher of <code>T</code> must declare a typedef like:</p>
<div class="fragment"><div class="line"><span class="keyword">using</span> is_gtest_matcher = void;</div>
</div><!-- fragment --><p>and supports the following operations:</p>
<div class="fragment"><div class="line"><span class="comment">// Match a value and optionally explain into an ostream.</span></div>
<div class="line"><span class="keywordtype">bool</span> matched = matcher.MatchAndExplain(value, maybe_os);</div>
<div class="line"><span class="comment">// where `value` is of type `T` and</span></div>
<div class="line"><span class="comment">// `maybe_os` is of type `std::ostream*`, where it can be null if the caller</span></div>
<div class="line"><span class="comment">// is not interested in there textual explanation.</span></div>
<div class="line"> </div>
<div class="line">matcher.DescribeTo(os);</div>
<div class="line">matcher.DescribeNegationTo(os);</div>
<div class="line"><span class="comment">// where `os` is of type `std::ostream*`.</span></div>
</div><!-- fragment --><p>If you need a custom matcher but <code>Truly()</code> is not a good option (for example, you may not be happy with the way <code>Truly(predicate)</code> describes itself, or you may want your matcher to be polymorphic as <code>Eq(value)</code> is), you can define a matcher to do whatever you want in two steps: first implement the matcher interface, and then define a factory function to create a matcher instance. The second step is not strictly needed but it makes the syntax of using the matcher nicer.</p>
<p>For example, you can define a matcher to test whether an <code>int</code> is divisible by 7 and then use it like this:</p>
<div class="fragment"><div class="line">using ::testing::Matcher;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>DivisibleBy7Matcher {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">using</span> is_gtest_matcher = void;</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">bool</span> MatchAndExplain(<span class="keywordtype">int</span> n, std::ostream*)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="keywordflow">return</span> (n % 7) == 0;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DescribeTo(std::ostream* os)<span class="keyword"> const </span>{</div>
<div class="line">    *os &lt;&lt; <span class="stringliteral">&quot;is divisible by 7&quot;</span>;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DescribeNegationTo(std::ostream* os)<span class="keyword"> const </span>{</div>
<div class="line">    *os &lt;&lt; <span class="stringliteral">&quot;is not divisible by 7&quot;</span>;</div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">Matcher&lt;int&gt; DivisibleBy7() {</div>
<div class="line">  <span class="keywordflow">return</span> DivisibleBy7Matcher();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(DivisibleBy7()));</div>
</div><!-- fragment --><p>You may improve the matcher message by streaming additional information to the <code>os</code> argument in <code>MatchAndExplain()</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>DivisibleBy7Matcher {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">bool</span> MatchAndExplain(<span class="keywordtype">int</span> n, std::ostream* os)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="keyword">const</span> <span class="keywordtype">int</span> remainder = n % 7;</div>
<div class="line">    <span class="keywordflow">if</span> (remainder != 0 &amp;&amp; os != <span class="keyword">nullptr</span>) {</div>
<div class="line">      *os &lt;&lt; <span class="stringliteral">&quot;the remainder is &quot;</span> &lt;&lt; remainder;</div>
<div class="line">    }</div>
<div class="line">    <span class="keywordflow">return</span> remainder == 0;</div>
<div class="line">  }</div>
<div class="line">  ...</div>
<div class="line">};</div>
</div><!-- fragment --><p>Then, <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-matchers_8h.html#ac31e206123aa702e1152bb2735b31409">EXPECT_THAT(x, DivisibleBy7())</a>;</code> may generate a message like this:</p>
<div class="fragment"><div class="line">Value of: x</div>
<div class="line">Expected: is divisible by 7</div>
<div class="line">  Actual: 23 (the remainder is 2)</div>
</div><!-- fragment --><p>{: .callout .tip} Tip: for convenience, <code>MatchAndExplain()</code> can take a <code>MatchResultListener*</code> instead of <code>std::ostream*</code>.</p>
<h2><a class="anchor" id="autotoc_md186"></a>
Writing New Polymorphic Matchers</h2>
<p>Expanding what we learned above to <em>polymorphic</em> matchers is now just as simple as adding templates in the right place.</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>NotNullMatcher {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">using</span> is_gtest_matcher = void;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// To implement a polymorphic matcher, we just need to make MatchAndExplain a</span></div>
<div class="line">  <span class="comment">// template on its first argument.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// In this example, we want to use NotNull() with any pointer, so</span></div>
<div class="line">  <span class="comment">// MatchAndExplain() accepts a pointer of any type as its first argument.</span></div>
<div class="line">  <span class="comment">// In general, you can define MatchAndExplain() as an ordinary method or</span></div>
<div class="line">  <span class="comment">// a method template, or even overload it.</span></div>
<div class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line">  <span class="keywordtype">bool</span> MatchAndExplain(T* p, std::ostream*)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="keywordflow">return</span> p != <span class="keyword">nullptr</span>;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes the property of a value matching this matcher.</span></div>
<div class="line">  <span class="keywordtype">void</span> DescribeTo(std::ostream&amp; os)<span class="keyword"> const </span>{ *os &lt;&lt; <span class="stringliteral">&quot;is not NULL&quot;</span>; }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes the property of a value NOT matching this matcher.</span></div>
<div class="line">  <span class="keywordtype">void</span> DescribeNegationTo(std::ostream* os)<span class="keyword"> const </span>{ *os &lt;&lt; <span class="stringliteral">&quot;is NULL&quot;</span>; }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">NotNullMatcher NotNull() {</div>
<div class="line">  <span class="keywordflow">return</span> NotNullMatcher();</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(NotNull()));  <span class="comment">// The argument must be a non-NULL pointer.</span></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md187"></a>
Legacy Matcher Implementation</h2>
<p>Defining matchers used to be somewhat more complicated, in which it required several supporting classes and virtual functions. To implement a matcher for type <code>T</code> using the legacy API you have to derive from <code>MatcherInterface&lt;T&gt;</code> and call <code>MakeMatcher</code> to construct the object.</p>
<p>The interface looks like this:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MatchResultListener {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  ...</div>
<div class="line">  <span class="comment">// Streams x to the underlying ostream; does nothing if the ostream</span></div>
<div class="line">  <span class="comment">// is NULL.</span></div>
<div class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line">  MatchResultListener&amp; <a class="code" href="namespacetesting.html#a2d038049296f23fb404311f974788cd3">operator&lt;&lt;</a>(<span class="keyword">const</span> T&amp; x);</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Returns the underlying ostream.</span></div>
<div class="line">  std::ostream* stream();</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line"><span class="keyword">class </span>MatcherInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~MatcherInterface();</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Returns true if and only if the matcher matches x; also explains the match</span></div>
<div class="line">  <span class="comment">// result to &#39;listener&#39;.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> MatchAndExplain(T x, MatchResultListener* listener) <span class="keyword">const</span> = 0;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes this matcher to an ostream.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> DescribeTo(std::ostream* os) <span class="keyword">const</span> = 0;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes the negation of this matcher to an ostream.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> DescribeNegationTo(std::ostream* os) <span class="keyword">const</span>;</div>
<div class="line">};</div>
<div class="ttc" id="anamespacetesting_html_a2d038049296f23fb404311f974788cd3"><div class="ttname"><a href="namespacetesting.html#a2d038049296f23fb404311f974788cd3">testing::operator&lt;&lt;</a></div><div class="ttdeci">std::ostream &amp; operator&lt;&lt;(std::ostream &amp;os, const Message &amp;sb)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googletest/include/gtest/gtest-message.h:199</div></div>
</div><!-- fragment --><p>Fortunately, most of the time you can define a polymorphic matcher easily with the help of <code>MakePolymorphicMatcher()</code>. Here's how you can define <code>NotNull()</code> as an example:</p>
<div class="fragment"><div class="line">using ::testing::MakePolymorphicMatcher;</div>
<div class="line">using ::testing::MatchResultListener;</div>
<div class="line">using ::testing::PolymorphicMatcher;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>NotNullMatcher {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="comment">// To implement a polymorphic matcher, first define a COPYABLE class</span></div>
<div class="line">  <span class="comment">// that has three members MatchAndExplain(), DescribeTo(), and</span></div>
<div class="line">  <span class="comment">// DescribeNegationTo(), like the following.</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// In this example, we want to use NotNull() with any pointer, so</span></div>
<div class="line">  <span class="comment">// MatchAndExplain() accepts a pointer of any type as its first argument.</span></div>
<div class="line">  <span class="comment">// In general, you can define MatchAndExplain() as an ordinary method or</span></div>
<div class="line">  <span class="comment">// a method template, or even overload it.</span></div>
<div class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line">  <span class="keywordtype">bool</span> MatchAndExplain(T* p,</div>
<div class="line">                       MatchResultListener* <span class="comment">/* listener */</span>)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="keywordflow">return</span> p != NULL;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes the property of a value matching this matcher.</span></div>
<div class="line">  <span class="keywordtype">void</span> DescribeTo(std::ostream* os)<span class="keyword"> const </span>{ *os &lt;&lt; <span class="stringliteral">&quot;is not NULL&quot;</span>; }</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes the property of a value NOT matching this matcher.</span></div>
<div class="line">  <span class="keywordtype">void</span> DescribeNegationTo(std::ostream* os)<span class="keyword"> const </span>{ *os &lt;&lt; <span class="stringliteral">&quot;is NULL&quot;</span>; }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// To construct a polymorphic matcher, pass an instance of the class</span></div>
<div class="line"><span class="comment">// to MakePolymorphicMatcher().  Note the return type.</span></div>
<div class="line">PolymorphicMatcher&lt;NotNullMatcher&gt; NotNull() {</div>
<div class="line">  <span class="keywordflow">return</span> MakePolymorphicMatcher(NotNullMatcher());</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line"> </div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(NotNull()));  <span class="comment">// The argument must be a non-NULL pointer.</span></div>
</div><!-- fragment --><p>{: .callout .note} <b>Note:</b> Your polymorphic matcher class does <b>not</b> need to inherit from <code>MatcherInterface</code> or any other class, and its methods do <b>not</b> need to be virtual.</p>
<p>Like in a monomorphic matcher, you may explain the match result by streaming additional information to the <code>listener</code> argument in <code>MatchAndExplain()</code>.</p>
<h2><a class="anchor" id="autotoc_md188"></a>
Writing New Cardinalities</h2>
<p>A cardinality is used in <code>Times()</code> to tell gMock how many times you expect a call to occur. It doesn't have to be exact. For example, you can say <code>AtLeast(5)</code> or <code>Between(2, 4)</code>.</p>
<p>If the <a href="gmock_cheat_sheet.md#CardinalityList">built-in set</a> of cardinalities doesn't suit you, you are free to define your own by implementing the following interface (in namespace <code>testing</code>):</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>CardinalityInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~CardinalityInterface();</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Returns true if and only if call_count calls will satisfy this cardinality.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> IsSatisfiedByCallCount(<span class="keywordtype">int</span> call_count) <span class="keyword">const</span> = 0;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Returns true if and only if call_count calls will saturate this</span></div>
<div class="line">  <span class="comment">// cardinality.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">bool</span> IsSaturatedByCallCount(<span class="keywordtype">int</span> call_count) <span class="keyword">const</span> = 0;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Describes self to an ostream.</span></div>
<div class="line">  <span class="keyword">virtual</span> <span class="keywordtype">void</span> DescribeTo(std::ostream* os) <span class="keyword">const</span> = 0;</div>
<div class="line">};</div>
</div><!-- fragment --><p>For example, to specify that a call must occur even number of times, you can write</p>
<div class="fragment"><div class="line">using ::testing::Cardinality;</div>
<div class="line">using ::testing::CardinalityInterface;</div>
<div class="line">using ::testing::MakeCardinality;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>EvenNumberCardinality : <span class="keyword">public</span> CardinalityInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">bool</span> IsSatisfiedByCallCount(<span class="keywordtype">int</span> call_count)<span class="keyword"> const override </span>{</div>
<div class="line">    <span class="keywordflow">return</span> (call_count % 2) == 0;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">bool</span> IsSaturatedByCallCount(<span class="keywordtype">int</span> call_count)<span class="keyword"> const override </span>{</div>
<div class="line">    <span class="keywordflow">return</span> <span class="keyword">false</span>;</div>
<div class="line">  }</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">void</span> DescribeTo(std::ostream* os)<span class="keyword"> const </span>{</div>
<div class="line">    *os &lt;&lt; <span class="stringliteral">&quot;called even number of times&quot;</span>;</div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">Cardinality EvenNumber() {</div>
<div class="line">  <span class="keywordflow">return</span> MakeCardinality(<span class="keyword">new</span> EvenNumberCardinality);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Bar(3))</div>
<div class="line">      .Times(EvenNumber());</div>
</div><!-- fragment --><h2><a class="anchor" id="QuickNewActions"></a>
Writing New Actions Quickly</h2>
<p>If the built-in actions don't work for you, you can easily define your own one. Just define a functor class with a (possibly templated) call operator, matching the signature of your action.</p>
<div class="fragment"><div class="line"><span class="keyword">struct </span>Increment {</div>
<div class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt;</div>
<div class="line">  T operator()(T* arg) {</div>
<div class="line">    <span class="keywordflow">return</span> ++(*arg);</div>
<div class="line">  }</div>
<div class="line">}</div>
</div><!-- fragment --><p>The same approach works with stateful functors (or any callable, really):</p>
<div class="fragment"><div class="line">struct MultiplyBy {</div>
<div class="line">  template &lt;typename T&gt;</div>
<div class="line">  T operator()(T arg) { return arg * multiplier; }</div>
<div class="line"> </div>
<div class="line">  int multiplier;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">// Then use:</div>
<div class="line">// EXPECT_CALL(...).WillOnce(MultiplyBy{7});</div>
</div><!-- fragment --><h3><a class="anchor" id="autotoc_md189"></a>
Legacy macro-based Actions</h3>
<p>Before C++11, the functor-based actions were not supported; the old way of writing actions was through a set of <code>ACTION*</code> macros. We suggest to avoid them in new code; they hide a lot of logic behind the macro, potentially leading to harder-to-understand compiler errors. Nevertheless, we cover them here for completeness.</p>
<p>By writing</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION</a>(name) { statements; }</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h_html_a7af7137aa4871df4235881af377205fe"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION</a></div><div class="ttdeci">#define ACTION(name)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1627</div></div>
</div><!-- fragment --><p>in a namespace scope (i.e. not inside a class or function), you will define an action with the given name that executes the statements. The value returned by <code>statements</code> will be used as the return value of the action. Inside the statements, you can refer to the K-th (0-based) argument of the mock function as <code>argK</code>. For example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION</a>(IncrementArg1) { <span class="keywordflow">return</span> ++(*arg1); }</div>
</div><!-- fragment --><p>allows you to write</p>
<div class="fragment"><div class="line">... WillOnce(IncrementArg1());</div>
</div><!-- fragment --><p>Note that you don't need to specify the types of the mock function arguments. Rest assured that your code is type-safe though: you'll get a compiler error if <code>*arg1</code> doesn't support the <code>++</code> operator, or if the type of <code>++(*arg1)</code> isn't compatible with the mock function's return type.</p>
<p>Another example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION</a>(Foo) {</div>
<div class="line">  (*arg2)(5);</div>
<div class="line">  Blah();</div>
<div class="line">  *arg1 = 0;</div>
<div class="line">  <span class="keywordflow">return</span> arg0;</div>
<div class="line">}</div>
</div><!-- fragment --><p>defines an action <code>Foo()</code> that invokes argument #2 (a function pointer) with 5, calls function <code>Blah()</code>, sets the value pointed to by argument #1 to 0, and returns argument #0.</p>
<p>For more convenience and flexibility, you can also use the following pre-defined symbols in the body of <code>ACTION</code>:</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadLeft"><code>argK_type</code>   </th><th class="markdownTableHeadLeft">The type of the K-th (0-based) argument of the mock function    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyLeft"><code>args</code>   </td><td class="markdownTableBodyLeft">All arguments of the mock function as a tuple    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyLeft"><code>args_type</code>   </td><td class="markdownTableBodyLeft">The type of all arguments of the mock function as a tuple    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyLeft"><code>return_type</code>   </td><td class="markdownTableBodyLeft">The return type of the mock function    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyLeft"><code>function_type</code>   </td><td class="markdownTableBodyLeft">The type of the mock function   </td></tr>
</table>
<p>For example, when using an <code>ACTION</code> as a stub action for mock function:</p>
<div class="fragment"><div class="line"><span class="keywordtype">int</span> DoSomething(<span class="keywordtype">bool</span> flag, <span class="keywordtype">int</span>* ptr);</div>
</div><!-- fragment --><p>we have:</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadNone">Pre-defined Symbol   </th><th class="markdownTableHeadNone">Is Bound To    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>arg0</code>   </td><td class="markdownTableBodyNone">the value of <code>flag</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>arg0_type</code>   </td><td class="markdownTableBodyNone">the type <code>bool</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>arg1</code>   </td><td class="markdownTableBodyNone">the value of <code>ptr</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>arg1_type</code>   </td><td class="markdownTableBodyNone">the type <code>int*</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>args</code>   </td><td class="markdownTableBodyNone">the tuple <code>(flag, ptr)</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>args_type</code>   </td><td class="markdownTableBodyNone">the type <code>std::tuple&lt;bool, int*&gt;</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code>return_type</code>   </td><td class="markdownTableBodyNone">the type <code>int</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>function_type</code>   </td><td class="markdownTableBodyNone">the type <code>int(bool, int*)</code>   </td></tr>
</table>
<h3><a class="anchor" id="autotoc_md190"></a>
Legacy macro-based parameterized Actions</h3>
<p>Sometimes you'll want to parameterize an action you define. For that we have another macro</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(name, param) { statements; }</div>
</div><!-- fragment --><p>For example,</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(Add, n) { <span class="keywordflow">return</span> arg0 + n; }</div>
</div><!-- fragment --><p>will allow you to write</p>
<div class="fragment"><div class="line"><span class="comment">// Returns argument #0 + 5.</span></div>
<div class="line">... WillOnce(Add(5));</div>
</div><!-- fragment --><p>For convenience, we use the term <em>arguments</em> for the values used to invoke the mock function, and the term <em>parameters</em> for the values used to instantiate an action.</p>
<p>Note that you don't need to provide the type of the parameter either. Suppose the parameter is named <code>param</code>, you can also use the gMock-defined symbol <code>param_type</code> to refer to the type of the parameter as inferred by the compiler. For example, in the body of <code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P(Add, n)</a></code> above, you can write <code>n_type</code> for the type of <code>n</code>.</p>
<p>gMock also provides <code>ACTION_P2</code>, <code>ACTION_P3</code>, and etc to support multi-parameter actions. For example,</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#ade0284b965683ea4d6449322becf3ba6">ACTION_P2</a>(ReturnDistanceTo, x, y) {</div>
<div class="line">  <span class="keywordtype">double</span> dx = arg0 - x;</div>
<div class="line">  <span class="keywordtype">double</span> dy = arg1 - y;</div>
<div class="line">  <span class="keywordflow">return</span> sqrt(dx*dx + dy*dy);</div>
<div class="line">}</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h_html_ade0284b965683ea4d6449322becf3ba6"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#ade0284b965683ea4d6449322becf3ba6">ACTION_P2</a></div><div class="ttdeci">#define ACTION_P2(name,...)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:1654</div></div>
</div><!-- fragment --><p>lets you write</p>
<div class="fragment"><div class="line">... WillOnce(ReturnDistanceTo(5.0, 26.5));</div>
</div><!-- fragment --><p>You can view <code>ACTION</code> as a degenerated parameterized action where the number of parameters is 0.</p>
<p>You can also easily define actions overloaded on the number of parameters:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(Plus, a) { ... }</div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#ade0284b965683ea4d6449322becf3ba6">ACTION_P2</a>(Plus, a, b) { ... }</div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md191"></a>
Restricting the Type of an Argument or Parameter in an ACTION</h2>
<p>For maximum brevity and reusability, the <code>ACTION*</code> macros don't ask you to provide the types of the mock function arguments and the action parameters. Instead, we let the compiler infer the types for us.</p>
<p>Sometimes, however, we may want to be more explicit about the types. There are several tricks to do that. For example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION</a>(Foo) {</div>
<div class="line">  <span class="comment">// Makes sure arg0 can be converted to int.</span></div>
<div class="line">  <span class="keywordtype">int</span> n = arg0;</div>
<div class="line">  ... use n instead of arg0 here ...</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P</a>(Bar, param) {</div>
<div class="line">  <span class="comment">// Makes sure the type of arg1 is const char*.</span></div>
<div class="line">  ::testing::StaticAssertTypeEq&lt;const char*, arg1_type&gt;();</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Makes sure param can be converted to bool.</span></div>
<div class="line">  <span class="keywordtype">bool</span> flag = param;</div>
<div class="line">}</div>
</div><!-- fragment --><p>where <code>StaticAssertTypeEq</code> is a compile-time assertion in googletest that verifies two types are the same.</p>
<h2><a class="anchor" id="autotoc_md192"></a>
Writing New Action Templates Quickly</h2>
<p>Sometimes you want to give an action explicit template parameters that cannot be inferred from its value parameters. <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-more-actions_8h.html#ad04fa741f313f0c23924d61fcfb1536d">ACTION_TEMPLATE()</a></code> supports that and can be viewed as an extension to <code><a class="el" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION()</a></code> and <code>ACTION_P*()</code>.</p>
<p>The syntax:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-more-actions_8h.html#ad04fa741f313f0c23924d61fcfb1536d">ACTION_TEMPLATE</a>(ActionName,</div>
<div class="line">                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),</div>
<div class="line">                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }</div>
<div class="ttc" id="acmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-more-actions_8h_html_ad04fa741f313f0c23924d61fcfb1536d"><div class="ttname"><a href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-more-actions_8h.html#ad04fa741f313f0c23924d61fcfb1536d">ACTION_TEMPLATE</a></div><div class="ttdeci">#define ACTION_TEMPLATE(name, template_params, value_params)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-more-actions.h:428</div></div>
</div><!-- fragment --><p>defines an action template that takes <em>m</em> explicit template parameters and <em>n</em> value parameters, where <em>m</em> is in [1, 10] and <em>n</em> is in [0, 10]. <code>name_i</code> is the name of the <em>i</em>-th template parameter, and <code>kind_i</code> specifies whether it's a <code>typename</code>, an integral constant, or a template. <code>p_i</code> is the name of the <em>i</em>-th value parameter.</p>
<p>Example:</p>
<div class="fragment"><div class="line"><span class="comment">// DuplicateArg&lt;k, T&gt;(output) converts the k-th argument of the mock</span></div>
<div class="line"><span class="comment">// function to type T and copies it to *output.</span></div>
<div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-more-actions_8h.html#ad04fa741f313f0c23924d61fcfb1536d">ACTION_TEMPLATE</a>(DuplicateArg,</div>
<div class="line">                <span class="comment">// Note the comma between int and k:</span></div>
<div class="line">                HAS_2_TEMPLATE_PARAMS(<span class="keywordtype">int</span>, k, <span class="keyword">typename</span>, T),</div>
<div class="line">                AND_1_VALUE_PARAMS(output)) {</div>
<div class="line">  *output = T(std::get&lt;k&gt;(args));</div>
<div class="line">}</div>
</div><!-- fragment --><p>To create an instance of an action template, write:</p>
<div class="fragment"><div class="line">ActionName&lt;t1, ..., t_m&gt;(v1, ..., v_n)</div>
</div><!-- fragment --><p>where the <code>t</code>s are the template arguments and the <code>v</code>s are the value arguments. The value argument types are inferred by the compiler. For example:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">...</div>
<div class="line">  <span class="keywordtype">int</span> n;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock, Foo).WillOnce(DuplicateArg&lt;1, unsigned char&gt;(&amp;n));</div>
</div><!-- fragment --><p>If you want to explicitly specify the value argument types, you can provide additional template arguments:</p>
<div class="fragment"><div class="line">ActionName&lt;t1, ..., t_m, u1, ..., u_k&gt;(v1, ..., v_n)</div>
</div><!-- fragment --><p>where <code>u_i</code> is the desired type of <code>v_i</code>.</p>
<p><code>ACTION_TEMPLATE</code> and <code>ACTION</code>/<code>ACTION_P*</code> can be overloaded on the number of value parameters, but not on the number of template parameters. Without the restriction, the meaning of the following is unclear:</p>
<div class="fragment"><div class="line">OverloadedAction&lt;int, bool&gt;(x);</div>
</div><!-- fragment --><p>Are we using a single-template-parameter action where <code>bool</code> refers to the type of <code>x</code>, or a two-template-parameter action where the compiler is asked to infer the type of <code>x</code>?</p>
<h2><a class="anchor" id="autotoc_md193"></a>
Using the ACTION Object's Type</h2>
<p>If you are writing a function that returns an <code>ACTION</code> object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple:</p>
<table class="markdownTable">
<tr class="markdownTableHead">
<th class="markdownTableHeadNone">Given Definition   </th><th class="markdownTableHeadNone">Expression   </th><th class="markdownTableHeadNone">Has Type    </th></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#a7af7137aa4871df4235881af377205fe">ACTION(Foo)</a></code>   </td><td class="markdownTableBodyNone"><code>Foo()</code>   </td><td class="markdownTableBodyNone"><code>FooAction</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())</code>   </td><td class="markdownTableBodyNone"><code>Foo&lt;t1, ..., t_m&gt;()</code>   </td><td class="markdownTableBodyNone"><code>FooAction&lt;t1, ..., t_m&gt;</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#af5f47e069acb517db9f743f029471aa7">ACTION_P(Bar, param)</a></code>   </td><td class="markdownTableBodyNone"><code>Bar(int_value)</code>   </td><td class="markdownTableBodyNone"><code>BarActionP&lt;int&gt;</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))</code>   </td><td class="markdownTableBodyNone"><code>Bar&lt;t1, ..., t_m&gt;(int_value)</code>   </td><td class="markdownTableBodyNone"><code>BarActionP&lt;t1, ..., t_m, int&gt;</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone"><code><a class="el" href="cmake-build-release_2googletest-src_2googlemock_2include_2gmock_2gmock-actions_8h.html#ade0284b965683ea4d6449322becf3ba6">ACTION_P2(Baz, p1, p2)</a></code>   </td><td class="markdownTableBodyNone"><code>Baz(bool_value, int_value)</code>   </td><td class="markdownTableBodyNone"><code>BazActionP2&lt;bool, int&gt;</code>    </td></tr>
<tr class="markdownTableRowEven">
<td class="markdownTableBodyNone"><code>ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))</code>   </td><td class="markdownTableBodyNone"><code>Baz&lt;t1, ..., t_m&gt;(bool_value, int_value)</code>   </td><td class="markdownTableBodyNone"><code>BazActionP2&lt;t1, ..., t_m, bool, int&gt;</code>    </td></tr>
<tr class="markdownTableRowOdd">
<td class="markdownTableBodyNone">...   </td><td class="markdownTableBodyNone">...   </td><td class="markdownTableBodyNone">...   </td></tr>
</table>
<p>Note that we have to pick different suffixes (<code>Action</code>, <code>ActionP</code>, <code>ActionP2</code>, and etc) for actions with different numbers of value parameters, or the action definitions cannot be overloaded on the number of them.</p>
<h2><a class="anchor" id="NewMonoActions"></a>
Writing New Monomorphic Actions</h2>
<p>While the <code>ACTION*</code> macros are very convenient, sometimes they are inappropriate. For example, despite the tricks shown in the previous recipes, they don't let you directly specify the types of the mock function arguments and the action parameters, which in general leads to unoptimized compiler error messages that can baffle unfamiliar users. They also don't allow overloading actions based on parameter types without jumping through some hoops.</p>
<p>An alternative to the <code>ACTION*</code> macros is to implement <code><a class="el" href="classtesting_1_1_action_interface.html">testing::ActionInterface</a>&lt;F&gt;</code>, where <code>F</code> is the type of the mock function in which the action will be used. For example:</p>
<div class="fragment"><div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> F&gt;</div>
<div class="line"><span class="keyword">class </span>ActionInterface {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">virtual</span> ~ActionInterface();</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// Performs the action.  Result is the return type of function type</span></div>
<div class="line">  <span class="comment">// F, and ArgumentTuple is the tuple of arguments of F.</span></div>
<div class="line">  <span class="comment">//</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// For example, if F is int(bool, const string&amp;), then Result would</span></div>
<div class="line">  <span class="comment">// be int, and ArgumentTuple would be std::tuple&lt;bool, const string&amp;&gt;.</span></div>
<div class="line">  <span class="keyword">virtual</span> Result Perform(<span class="keyword">const</span> ArgumentTuple&amp; args) = 0;</div>
<div class="line">};</div>
</div><!-- fragment --><div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line">using ::testing::Action;</div>
<div class="line">using ::testing::ActionInterface;</div>
<div class="line"><a class="code" href="namespacetesting.html#aa254d28c8d883899cbf11ea2f05fc195">using ::testing::MakeAction</a>;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">typedef</span> <span class="keywordtype">int</span> IncrementMethod(<span class="keywordtype">int</span>*);</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>IncrementArgumentAction : <span class="keyword">public</span> ActionInterface&lt;IncrementMethod&gt; {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keywordtype">int</span> Perform(<span class="keyword">const</span> std::tuple&lt;int*&gt;&amp; args)<span class="keyword"> override </span>{</div>
<div class="line">    <span class="keywordtype">int</span>* p = std::get&lt;0&gt;(args);  <span class="comment">// Grabs the first argument.</span></div>
<div class="line">    <span class="keywordflow">return</span> *p++;</div>
<div class="line">  }</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">Action&lt;IncrementMethod&gt; IncrementArgument() {</div>
<div class="line">  <span class="keywordflow">return</span> <a class="code" href="namespacetesting.html#aa254d28c8d883899cbf11ea2f05fc195">MakeAction</a>(<span class="keyword">new</span> IncrementArgumentAction);</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line">...</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, Baz(_))</div>
<div class="line">      .WillOnce(IncrementArgument());</div>
<div class="line"> </div>
<div class="line">  <span class="keywordtype">int</span> n = 5;</div>
<div class="line">  foo.Baz(&amp;n);  <span class="comment">// Should return 5 and change n to 6.</span></div>
<div class="ttc" id="anamespacetesting_html_aa254d28c8d883899cbf11ea2f05fc195"><div class="ttname"><a href="namespacetesting.html#aa254d28c8d883899cbf11ea2f05fc195">testing::MakeAction</a></div><div class="ttdeci">Action&lt; F &gt; MakeAction(ActionInterface&lt; F &gt; *impl)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:583</div></div>
</div><!-- fragment --><h2><a class="anchor" id="NewPolyActions"></a>
Writing New Polymorphic Actions</h2>
<p>The previous recipe showed you how to define your own action. This is all good, except that you need to know the type of the function in which the action will be used. Sometimes that can be a problem. For example, if you want to use the action in functions with <em>different</em> types (e.g. like <code><a class="el" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return()</a></code> and <code><a class="el" href="namespacetesting.html#a6e0d2e2c84a1fc7477fcb84be09d5560">SetArgPointee()</a></code>).</p>
<p>If an action can be used in several types of mock functions, we say it's <em>polymorphic</em>. The <code><a class="el" href="namespacetesting.html#a45df529b8166936d970884383f0ede82">MakePolymorphicAction()</a></code> function template makes it easy to define such an action:</p>
<div class="fragment"><div class="line"><span class="keyword">namespace </span><a class="code" href="namespacetesting.html">testing</a> {</div>
<div class="line"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Impl&gt;</div>
<div class="line">PolymorphicAction&lt;Impl&gt; <a class="code" href="namespacetesting.html#a45df529b8166936d970884383f0ede82">MakePolymorphicAction</a>(<span class="keyword">const</span> Impl&amp; impl);</div>
<div class="line">}  <span class="comment">// namespace testing</span></div>
<div class="ttc" id="anamespacetesting_html"><div class="ttname"><a href="namespacetesting.html">testing</a></div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:154</div></div>
<div class="ttc" id="anamespacetesting_html_a45df529b8166936d970884383f0ede82"><div class="ttname"><a href="namespacetesting.html#a45df529b8166936d970884383f0ede82">testing::MakePolymorphicAction</a></div><div class="ttdeci">PolymorphicAction&lt; Impl &gt; MakePolymorphicAction(const Impl &amp;impl)</div><div class="ttdef"><b>Definition:</b> cmake-build-debug/googletest-src/googlemock/include/gmock/gmock-actions.h:595</div></div>
</div><!-- fragment --><p>As an example, let's define an action that returns the second argument in the mock function's argument list. The first step is to define an implementation class:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>ReturnSecondArgumentAction {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <span class="keyword">template</span> &lt;<span class="keyword">typename</span> Result, <span class="keyword">typename</span> ArgumentTuple&gt;</div>
<div class="line">  Result Perform(<span class="keyword">const</span> ArgumentTuple&amp; args)<span class="keyword"> const </span>{</div>
<div class="line">    <span class="comment">// To get the i-th (0-based) argument, use std::get(args).</span></div>
<div class="line">    <span class="keywordflow">return</span> std::get&lt;1&gt;(args);</div>
<div class="line">  }</div>
<div class="line">};</div>
</div><!-- fragment --><p>This implementation class does <em>not</em> need to inherit from any particular class. What matters is that it must have a <code>Perform()</code> method template. This method template takes the mock function's arguments as a tuple in a <b>single</b> argument, and returns the result of the action. It can be either <code>const</code> or not, but must be invokable with exactly one template argument, which is the result type. In other words, you must be able to call <code>Perform&lt;R&gt;(args)</code> where <code>R</code> is the mock function's return type and <code>args</code> is its arguments in a tuple.</p>
<p>Next, we use <code><a class="el" href="namespacetesting.html#a45df529b8166936d970884383f0ede82">MakePolymorphicAction()</a></code> to turn an instance of the implementation class into the polymorphic action we need. It will be convenient to have a wrapper for this:</p>
<div class="fragment"><div class="line"><a class="code" href="namespacetesting.html#a45df529b8166936d970884383f0ede82">using ::testing::MakePolymorphicAction</a>;</div>
<div class="line">using ::testing::PolymorphicAction;</div>
<div class="line"> </div>
<div class="line">PolymorphicAction&lt;ReturnSecondArgumentAction&gt; ReturnSecondArgument() {</div>
<div class="line">  <span class="keywordflow">return</span> <a class="code" href="namespacetesting.html#a45df529b8166936d970884383f0ede82">MakePolymorphicAction</a>(ReturnSecondArgumentAction());</div>
<div class="line">}</div>
</div><!-- fragment --><p>Now, you can use this polymorphic action the same way you use the built-in ones:</p>
<div class="fragment"><div class="line">using ::testing::_;</div>
<div class="line"> </div>
<div class="line"><span class="keyword">class </span>MockFoo : <span class="keyword">public</span> Foo {</div>
<div class="line"> <span class="keyword">public</span>:</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">int</span>, DoThis, (<span class="keywordtype">bool</span> flag, <span class="keywordtype">int</span> n), (<span class="keyword">override</span>));</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-function-mocker_8h.html#a05ffc29d0784b131ee178da190d31397">MOCK_METHOD</a>(<span class="keywordtype">string</span>, DoThat, (<span class="keywordtype">int</span> x, <span class="keyword">const</span> <span class="keywordtype">char</span>* str1, <span class="keyword">const</span> <span class="keywordtype">char</span>* str2),</div>
<div class="line">              (<span class="keyword">override</span>));</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line">  ...</div>
<div class="line">  MockFoo foo;</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThis).WillOnce(ReturnSecondArgument());</div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(foo, DoThat).WillOnce(ReturnSecondArgument());</div>
<div class="line">  ...</div>
<div class="line">  foo.DoThis(<span class="keyword">true</span>, 5);  <span class="comment">// Will return 5.</span></div>
<div class="line">  foo.DoThat(1, <span class="stringliteral">&quot;Hi&quot;</span>, <span class="stringliteral">&quot;Bye&quot;</span>);  <span class="comment">// Will return &quot;Hi&quot;.</span></div>
</div><!-- fragment --><h2><a class="anchor" id="autotoc_md194"></a>
Teaching gMock How to Print Your Values</h2>
<p>When an uninteresting or unexpected call occurs, gMock prints the argument values and the stack trace to help you debug. Assertion macros like <code>EXPECT_THAT</code> and <code>EXPECT_EQ</code> also print the values in question when the assertion fails. gMock and googletest do this using googletest's user-extensible value printer.</p>
<p>This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the <code>&lt;&lt;</code> operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. <a href="advanced.md#teaching-googletest-how-to-print-your-values">The GoogleTest advanced guide</a> explains how to extend the printer to do a better job at printing your particular type than to dump the bytes.</p>
<h1><a class="anchor" id="autotoc_md195"></a>
Useful Mocks Created Using gMock</h1>
<h2><a class="anchor" id="MockFunction"></a>
Mock std::function</h2>
<p><code>std::function</code> is a general function type introduced in C++11. It is a preferred way of passing callbacks to new interfaces. Functions are copiable, and are not usually passed around by pointer, which makes them tricky to mock. But fear not - <code>MockFunction</code> can help you with that.</p>
<p><code>MockFunction&lt;R(T1, ..., Tn)&gt;</code> has a mock method <code>Call()</code> with the signature:</p>
<div class="fragment"><div class="line">R Call(T1, ..., Tn);</div>
</div><!-- fragment --><p>It also has a <code>AsStdFunction()</code> method, which creates a <code>std::function</code> proxy forwarding to Call:</p>
<div class="fragment"><div class="line">std::function&lt;R(T1, ..., Tn)&gt; AsStdFunction();</div>
</div><!-- fragment --><p>To use <code>MockFunction</code>, first create <code>MockFunction</code> object and set up expectations on its <code>Call</code> method. Then pass proxy obtained from <code>AsStdFunction()</code> to the code you are testing. For example:</p>
<div class="fragment"><div class="line"><a class="code" href="cmake-build-debug_2googletest-src_2googletest_2include_2gtest_2gtest_8h.html#ab5540a6d621853916be8240ff51819cf">TEST</a>(FooTest, RunsCallbackWithBarArgument) {</div>
<div class="line">  <span class="comment">// 1. Create a mock object.</span></div>
<div class="line">  MockFunction&lt;int(<span class="keywordtype">string</span>)&gt; mock_function;</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// 2. Set expectations on Call() method.</span></div>
<div class="line">  <a class="code" href="cmake-build-debug_2googletest-src_2googlemock_2include_2gmock_2gmock-spec-builders_8h.html#a535a6156de72c1a2e25a127e38ee5232">EXPECT_CALL</a>(mock_function, Call(<span class="stringliteral">&quot;bar&quot;</span>)).WillOnce(<a class="code" href="namespacetesting.html#adae3994eb444d1ad2dd602454b854663">Return</a>(1));</div>
<div class="line"> </div>
<div class="line">  <span class="comment">// 3. Exercise code that uses std::function.</span></div>
<div class="line">  Foo(mock_function.AsStdFunction());</div>
<div class="line">  <span class="comment">// Foo&#39;s signature can be either of:</span></div>
<div class="line">  <span class="comment">// void Foo(const std::function&lt;int(string)&gt;&amp; fun);</span></div>
<div class="line">  <span class="comment">// void Foo(std::function&lt;int(string)&gt; fun);</span></div>
<div class="line"> </div>
<div class="line">  <span class="comment">// 4. All expectations will be verified when mock_function</span></div>
<div class="line">  <span class="comment">//     goes out of scope and is destroyed.</span></div>
<div class="line">}</div>
</div><!-- fragment --><p>Remember that function objects created with <code>AsStdFunction()</code> are just forwarders. If you create multiple of them, they will share the same set of expectations.</p>
<p>Although <code>std::function</code> supports unlimited number of arguments, <code>MockFunction</code> implementation is limited to ten. If you ever hit that limit... well, your callback has bigger problems than being mockable. :-) </p>
</div></div><!-- contents -->
</div><!-- PageDoc -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by&#160;<a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.2
</small></address>
</body>
</html>
